java注释 正则表达式,在Java正则表达式中包含注释

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 working. I finally caught my bug and will post it as an answer but I'd be grateful for any other advice on maintaining regexes

As an example I want to comment the subcomponents (of patternS) in a simple name parser:

String testTarget = "Waldorf T. Flywheel";

String patternS = "([A-Za-z]+)\\s+([A-Z]\\.)?\\s+([A-Za-z]+)";

Pattern pattern = Pattern.compile(patternS, Pattern.COMMENTS);

Assert.assertTrue(pattern.matcher(testTarget).matches());

EDIT: I would be grateful for examples of the (?x) format as well.

EDIT: @geowa4 has a good suggestion which avoids embedded comments. Sinnce java and others have provided for embedded comments what are the cases where they are useful? (I think I have a case but I'd be interested to see others).

EDIT: As noted below @mikej the regex does not support the optional initial well and would be better as:

String patternS = "([A-Za-z]+)\\s+([A-Z]\\.\\s+)?([A-Za-z]+)";

but that would end up extracting space in the initial

解决方案

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值