Reusing a character class in a regular expression

这一生的挚爱 提交于 2019-12-07 09:30:13

问题


In order to keep a regular expression more brief, is there a shorthand way to refer to a character class that occurs earlier in the same regular expression?

Example

Is there a way to shorten the following:

[acegikmoqstz@#&].*[acegikmoqstz@#&].*[acegikmoqstz@#&]


回答1:


Keep in mind that regex features are dependant on the language being used.

With Java, you can do this:

[acegikmoqstz@#&](?:.*[acegikmoqstz@#&]){2}

But that's all, with java you can't refer to named subpattern.

With PHP you can do that:

(?(DEFINE)(?<a>[acegikmoqstz@#&]))\g<a>(?:.*\g<a>){2}


来源:https://stackoverflow.com/questions/20109423/reusing-a-character-class-in-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!