If Else 正则表达式匹配 [英] If Else regex matching
问题描述
我想构建一个正则表达式,在其中搜索包含连续 12 位数字的字符串.如果没有匹配项,请查找一行中只有 10 位数字的字符串.
例如:
a123456789012aa1234567890a
会回来:
123456789012
如果输入是:
a1234aa1234567890a
它会返回:
1234567890
我设法为各个操作创建了正则表达式,将 (?<!\d)\d{10}(?!\d)
输入 10 位数字和 (?<!\d)\d{12}(?!\d)
用于 12 位数字,但我无法以 if-else 样式将它们分组.
我尝试了以下方法:
(?(?
但如果第一个模式不匹配,则正则表达式不会尝试匹配第二个模式,不返回任何内容
你可以像这样使用一个简单的正则表达式:
\d{12}|\d{10}
情况 2:
顺便说一句,如果您想捕获内容,请使用捕获组:
(\d{12}|\d{10})
I want to build a regex where it searches for a string containing 12 digits in a row. If there's no match, look for a string with only 10 digits in a row.
For example:
a123456789012a
a1234567890a
Would return:
123456789012
And if the input is:
a1234a
a1234567890a
It would return:
1234567890
I managed to create the regex for the individual operations, beeing (?<!\d)\d{10}(?!\d)
for 10 digits and (?<!\d)\d{12}(?!\d)
for 12 digits, but I can't group them up in a if-else style.
I tried the following:
(?(?<!\d)\d{12}(?!\d)|((?<!\d)\d{10}(?!\d)))
but if the first pattern don't match, the regex don't try to match the second, returning nothing
You can use a simple regex like this:
\d{12}|\d{10}
Look that I have not used multiline
nor global
flags. This way the pattern is going to find the first match you want.
Case 1:
Case 2:
BTW, use capturing groups if you want to capture the content:
(\d{12}|\d{10})
这篇关于If Else 正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!