If Else regex matching [duplicate]

感情迁移 提交于 2021-02-05 12:15:18

问题


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


回答1:


You can use a simple regex like this:

\d{12}|\d{10}

working demo

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})


来源:https://stackoverflow.com/questions/57698986/if-else-regex-matching

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