문제

Why doesn't the below regex print True?

print re.compile(r'^\b[a-z]\b$').search('(s)')

I want to match single char alphabeticals that may have non alphanumeric characters before and after, but do not have any more alphanumeric characters anywhere in the string. So the following should be matches:

'b'
'b)'
'(b)'
'b,

and the following should be misses:

'b(s)'
'blah(b)'
'bb)'
'b-b'
'bb'

The solutions here don't work.

도움이 되었습니까?

해결책 2

Ok here is the answer:

print re.compile(^[(,\[]?[a-z][),;\]]?[,;]?$).search('(s)')

It catches a variety of complex patterns for single character alphanumerics. I realize this is different than what I asked for but in reality it works better.

다른 팁

The ^ at the begining and $ at the end cause the expression to match only if the entire string is a single character. (Thus, they make each \b obsolete.) Remove the anchors to match inside a larger string:

print re.compile(r'\b[a-z]\b').search('b(s)')

Alternatively, ensure only one character like:

print re.compile(r'^\W*[a-z]\W*$').match('b(s)')

Note that in the first case, 'b-b' and 'blah(b)' will match because they contain single alphabetical characters not touching others inside them. In the second case, 'b(s)' will not be a match, because it contains two alphabetical characters, but the other four cases will match correctly, and all of the no-match cases will return None (false logical value) as intended.

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