0

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?

8
  • 1
    you need to use raw string literal r instead of re.escape p = re.compile(r"\d{1}\.?\d{0,2}\/10") Commented Jun 4, 2016 at 5:55
  • Change p = re.compile(re.escape("\d{1}\.?\d{0,2}\/10")) to p = re.compile(r"\d{1}\.?\d{0,2}\/10") it will work. Commented Jun 4, 2016 at 5:57
  • 1
    also, i suspect that you may have problem later while using match..because match matches only in starting of string.. Commented Jun 4, 2016 at 5:58
  • @rock321987 Please post your answer Commented Jun 4, 2016 at 6:00
  • well someone already posted..no need to add redundancy Commented Jun 4, 2016 at 6:01

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.