[英]Regular expression Java Merge Pattern
I've these three regular expressions. 我有这三个正则表达式。 They work individually but i would like to merge them in a single pattern. 它们单独工作,但我想将它们合并为一个模式。
regex1 = [0-9]{16}
regex2 = [0-9]{4}[-][0-9]{4}[-][0-9]{4}[-][0-9]{4}
regex3 = [0-9]{4}[ ][0-9]{4}[ ][0-9]{4}[ ][0-9]{4}
I use this method: 我使用这种方法:
Pattern.compile(regex);
Which is the regex string to merge them? 哪个正则表达式字符串可以合并它们?
You can use backreferences : 您可以使用反向引用 :
[0-9]{4}([ -]|)([0-9]{4}\1){2}[0-9]{4}
This will only match if the seperators are either all 仅当分隔符为全部时才匹配
\\1
means "this matches exactly what the first capturing group – expression in parentheses – matched". \\1
表示“这与第一个捕获组 (括号中的表达式)完全匹配”。
Since ([ -]|)
is that group, both other separators need to be the same for the pattern to match. 由于([ -]|)
是该组,因此要使模式匹配,其他两个分隔符都必须相同。
You can simplify it further to: 您可以将其进一步简化为:
\d{4}([ -]|)(\d{4}\1){2}\d{4}
The following should match anything the three patterns match: 以下应匹配三个模式匹配的任何内容:
regex = [0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}
That is, I'm assuming you are happy with either a hyphen, a space or nothing between the numbers? 也就是说,我假设您对连字符,空格或数字之间的任何内容都不满意?
Note: this will also match situations where you have any combination of the three, eg 注意:这也将匹配您将三者任意组合的情况,例如
0000-0000 00000000
which may not be desired? 这可能是不希望的?
Alternatively, if you need to match any of the three individual patterns then just concatenate them with |
或者,如果您需要匹配三个单独的模式中的任何一个,则只需将它们与|
连接即可|
, as follows: , 如下:
([0-9]{16})|([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4})|([0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4})
(Your original example appears to have unnecessary square brackets around the space and hyphen) (您的原始示例似乎在空格和连字符周围有不必要的方括号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.