Reputation: 7457
could somebody explain the difference between these two Regular Expression:
re.search('^[abcd]z$', noun)
and
re.search('[^abcd]z$', noun)
Thanks!
Upvotes: 1
Views: 66
Reputation: 879381
'^[abcd]z$'
must match starting at the beginning of the string.
'[^abcd]z$
matches anything with is not in the character class [abcd]
, followed by a z
.
As you can see, the ^
has vastly different meanings inside and outside of the brackets. Outside the brackets, ^
matches the start of the string, while if ^
is the first character inside brackets, it indicates a complementing set.
This matches, since 'dz'
starts with a character in [abcd]
.
In [102]: re.search('^[abcd]z', 'dz')
Out[102]: <_sre.SRE_Match at 0xa12b480>
This does not match since [^abcd]
matches anything but a
, b
, c
or d
.
In [103]: re.search('[^abcd]z', 'dz')
While this does match since e
is not in [abcd]
.
In [104]: re.search('[^abcd]z', 'ez')
Out[104]: <_sre.SRE_Match at 0xa12b3a0>
Per the docs:
'^'
: (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
'[]'
: Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.
Upvotes: 3