Including comments in Java regular expressions

后端 未结 3 1372
借酒劲吻你
借酒劲吻你 2021-01-04 04:41

I have some complex regular expressions which I need to comment for readability and maintenance. The Java spec is rather terse and I struggled for a long time getting this w

3条回答
  •  遥遥无期
    2021-01-04 05:34

    See the post by Martin Fowler on ComposedRegex for some more ideas on improving regexp readability. In summary, he advocates breaking down a complex regexp into smaller parts which can be given meaningful variable names. e.g.

    String mandatoryName = "([A-Za-z]+)";
    String mandatoryWhiteSpace = "\\s+";
    String optionalInitial = "([A-Z]\\.)?";
    String pattern = mandatoryName + mandatoryWhiteSpace + optionalInitial +
        mandatoryWhiteSpace + mandatoryName;
    

提交回复
热议问题