Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not being able to detect '-' character in regular expression [duplicate]

Tags:

python

regex

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?

like image 700
Mihika Avatar asked Dec 10 '18 05:12

Mihika


People also ask

How to check special characters in regular expression?

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 "(" .

What special characters need to be escaped in regex?

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.

What is\\ w in regex?

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

What is the regular expression for characters?

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.


1 Answers

- 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.
like image 199
DYZ Avatar answered Sep 27 '22 01:09

DYZ