Question

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.

Was it helpful?

Solution 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top