开发者

if else in regex

I need a regular expression, which catches a first expression. If its not found, catch the second one. The first one is a 2-4 long number with a following 'X', if it's not found, just catch the 2-4 long number without 'X'.

foo bar 321 string 1234X and so on // catch 1234X

I found a short example here (开发者_如何学JAVAa)?b(?(1)c|d) but i misinterpreted it.

(\d{2,4}X)?(?(1)(\d{2,4})X|\D(\d{2,4})\D)

It always finds the '321'. I tried several variations, but nothing works.


You could use:

/(?| .*? (\d{2,4}X) | (\d{2,4}) (?!X) )/xs

(Quote and escape it properly before use.)

Note that it will match 1111X in 1111111111111111111X, and also if the number is part of "words". If you don't want that use something like:

/(?| .*? \b(\d{2,4}X) | \b(\d{2,4}) ) \b /xs

Perl demo:

perl -E "say join',','foo 123 bar 345X 44 33X' =~ /(?| .*? (\d{2,4}X) | (\d{2,4}) (?!X) )/xs;"
345X


Why don't you just catch them all? By using alternatives with "|"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜