문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top