I am trying to test whether a character is a special character or not.
It fails for '-' character when I write the following code:
import re
s = '-'
regex = re.compile('[!@#$%^&*()-+]')
if regex.search(s) == None:
print("Not found")
else:
print("Found")
Output>>Not found
However, if I change the position of the '-' character in the pattern as follows (line 3 of code), it works correctly
import re
s = '-'
regex = re.compile('[!@#$%^&*()+-]')
if regex.search(s) == None:
print("Not found")
else:
print("Found")
Output>>Found
What is causing this difference and how can I make sure that the characters will be detected?
Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.
The RegExp \W Metacharacter in JavaScript is used to find the non word character i.e. characters which are not from a to z, A to Z, 0 to 9. It is same as [^a-zA-Z0-9].
A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.
-
is treated as a special character if it is not the last or the first character in a range and not escaped. So:
[-19]
or [19-]
or [1\-9]
is -
, 1
or 9
, but [1-9]
is anything between 1
and 9
, inclusive, but not -
itself.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With