Reputation: 384
I have a problem with my regex in Python 3.2
I want to make sure that a string matches my critera which is a letter (or number) then a symbol.
answer = bool(re.findall('[A-Z|1-9][^A-Z|1-9]',string))
This works as expected. If I test A#
I get True
and this works for all types of enteries. Accept when I do something such as T^
which returns False
. This is the same no matter what letter comes before the caret. Is this a problem with my Regex or is it Python?
Upvotes: 0
Views: 1716
Reputation: 1620
Give this a try :
^[A-Za-z|1-9][^A-Za-z|1-9]$
I tried to remove case sensitivity from your regex and this is also accepting T^. I have checked it on http://regexpal.com/
Here first ^ and last $ symbols are ment to be start and end of string.
Working Demo : Here
Upvotes: 0
Reputation: 5938
There are answers here that help but none have picked up in the ^
used in the character class, this means NOT ANY OF THESE THINGS
, so [^a]
is EVERYTHING but the letter a. You are saying `"none of the things after the ^ and before the nearest not-escaped ]"
As mentioned the or thing ... a character class is one big or!
[\^a]
matches ^ or an a. Be careful though, usually a backslash is taken as "the letter backslash" unless it actually escapes something, for example \k
is a backslash and a k, but \n
is a newline, \\n
is backslash (the letter) n.
PHP however is not that nice. You need "\\\\"
for the letter backslash, Given the thing after the backslash can be escaped (which is something the REGEX engine works out), PHP does not use "Oh you can't escape a k, he must therefore mean the letter backslash followed by k", it discards the backslash.
So many hours... just... awful.
Upvotes: 2
Reputation: 9641
Your regex is a little off.
[A-Z|1-9]
actually means:
a-z
|
literally1-9
.Try this:
[A-Z0-9][^A-Z0-9]
However, your regex SHOULD be matching T^
in any case...
Upvotes: 1