Add flexible rule based substitution system (#4047)