We present an algorithmic construction scheme for matrix-product-operator
(MPO) representations of arbitrary $U(1)$-invariant operators whenever there is
an expression of the local structure in terms of a finite-states machine (FSM).
Given a set of local operators as building blocks, the method automatizes two
major steps when constructing a $U(1)$-invariant MPO representation: (i) the
bookkeeping of auxiliary bond-index shifts arising from the application of
operators changing the local quantum numbers and (ii) the appearance of phase
factors due to particular commutation rules. The automatization is achieved by
post-processing the operator strings generated by the FSM. Consequently, MPO
representations of various types of $U(1)$-invariant operators can be
constructed generically in MPS algorithms reducing the necessity of expensive
MPO arithmetics. This is demonstrated by generating arbitrary products of
operators in terms of FSM, from which we obtain exact MPO representations for
the variance of the Hamiltonian of a $S=1$ Heisenberg chain.