I have this regex to identify if the line contains two underscores:
\s*_{2}(\w+)
Any space, two underscores and then a word. It turns out, I need to know also for no underscore at all, so I have:
\s*(\w+)
Optional spaces followed by a word. Then I get the group 1 which is my word. So far so good.
The problem is the action taken when two underscores are used, is almost identical to the code when no underscore are use ( except that I raise a flag )
if( s =~ uderscore ) {
takeGroup( 1 )
yada yada
flag = true
} else if( s =~ noUnderscore { 开发者_如何学运维
takeGroup( 1 )
yada yada
flag = false
}
I think there must be a better way instead of duplicating the whole regexp and test with and with out.
Use this regex instead:
\s*(_{2})?(\w+)
Then simply test for the presence of the first group -- if it's there, the underscores were present. What was group 1 will then become group 2.
\s*(__)?(\w+)
(__)?
is an optional group of two underscores. Note that the word will be in group 2 now instead of 1. You could use a non-capturing group (?:__)
instead if you wanted to not change the group numbering.
精彩评论