Enigmatic
Enigmatic

Reputation: 4138

Using regex to match a specific pattern in Python

I am trying to create regex that matches the following pattern:

Note : x is a number e.g. 2

Pattern:

u'id': u'x'                # x = Any Number e.g: u'id': u'2'

So far I have tried the folllowing:

Regex = re.findall(r"'(u'id':u\d)'", Data)

However, no matches are being found.

Upvotes: 1

Views: 154

Answers (3)

Sunny Aggarwal
Sunny Aggarwal

Reputation: 81

Try this:

str1 = "u'id': u'x'"

re.findall(r'u\'id\': u\'\d+\'',str1)

You need to escape single-quote(') because it's a special character

Upvotes: 1

James Monger
James Monger

Reputation: 10665

This regex will match your patterns:

u'id': u'(\d+)'

The important bits of the regex here are:

  • the brackets () which makes a capture group (so you can get the information
  • the digit marker \d which specifies any digit 0 - 9
  • the multiple marker + which means "at least 1"

Tested on the following patterns:

u'id': u'3'
u'id': u'20'
u'id': u'250'
u'id': u'6132838'

Upvotes: 2

anubhava
anubhava

Reputation: 784918

You have misplaced single quotes and you should use \d+ instead of just \d:

>>> s = "u'id': u'2'"
>>> re.findall(r"u'id'\s*:\s*u'\d+'", s)
["u'id': u'2'"]

Upvotes: 2

Related Questions