Meysam
Meysam

Reputation: 18127

Why is this regex not matched in python

I need to find "7.1/10" in "7.1/10&nb" with the following regex:

\d{1}\.?\d{0,2}\/10

But the following code does not match anything:

rating= "7.1/10&nb"
p = re.compile(re.escape("\d{1}\.?\d{0,2}\/10"))
m = p.match(rating)
if m:
    print("rating: {}".format(m.group()))
else:
    print("no match found in {}".format(rating))

What's the problem with my code?

Upvotes: 0

Views: 44

Answers (2)

J.Joe
J.Joe

Reputation: 664

p = re.compile(r"\d\.?\d{0,2}/10")

There are several problems in you re:

  • add 'r' for raw string or you will have to escape all '\': re.compile("\\d\\.?\\d{0,2}/10")
  • \d{1} can be \d
  • \/ can be /, no need to escape

Upvotes: 2

Rahul K P
Rahul K P

Reputation: 16081

Change only one line in your code.

p = re.compile(re.escape("\d{1}\.?\d{0,2}\/10")) to re.compile(r"\d{1}\.?\d{0,2}\/10")

It will work smoothly.

Upvotes: 1

Related Questions