0

I have this piece of code just for testing regular expressions in Python.

#!/usr/bin/python
import re

line = "(400,71.20,73.40) Cats are smarter than dogs"

matchObj = re.match( r'(\d{3}),(\d{2}.\d{2}),(\d{2}.\d{2})', line,re.I)

if matchObj:
   print "matchObj.group() : ", matchObj.group()
   print "matchObj.group(1) : ", matchObj.group(1)
   print "matchObj.group(2) : ", matchObj.group(2)
else:
   print "No match!!"

It's supposed to print 3 groups (400)(71.20)(73.40), but instead always prints "No Match!!".

Can someone help me?

Thanks in advance

taleinat
  • 8,441
  • 1
  • 30
  • 44
HIT_Braga
  • 1
  • 1
  • 2
  • 2
    you could try an online regex site like https://regex101.com/#python to debug your code – Erik Jul 08 '15 at 07:22

2 Answers2

1

It's because of the function re.match which tries to match from the start of the string. Since there is an unmatched ( present at the start, your regex fails. So adding a pattern to match the starting ( symbol in re.match will solves your problem.

re.match( r'\((\d{3}),(\d{2}\.\d{2}),(\d{2}\.\d{2})', line)

And also re.I is unneceassry here since we are matching chars other than alphabets.

or

I suggest you to use re.search to match a substring which exists anywhere.

re.search( r'(\d{3}),(\d{2}\.\d{2}),(\d{2}\.\d{2})', line)
Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Just include \( in your regex as match matches from beginning and your string has ( as start.

or simply use re.findall

line = "(400,71.20,73.40) Cats are smarter than dogs"

matchObj = re.findall( r'\((\d{3}),(\d{2}\.\d{2}),(\d{2}\.\d{2})', line)
print matchObj

OUTPUT: [('400', '71.20', '73.40')]

vks
  • 67,027
  • 10
  • 91
  • 124