1

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.

1
  • 1
    Try: r"u'id'\s*:\s*u'\d+'" Commented Sep 23, 2016 at 11:39

3 Answers 3

2

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

2 Comments

\s* matches 0 or more whitespaces. Double quotes or single quotes around the regex is needed as regex is of string type. Here since single quote is part of the regex itself we need to use double quote for regex string constant.
I wish I could tell you - think I was scrolling through old questions. Must have been a misclick :D
2

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'

Comments

1

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

3 Comments

Why escape single quotes when you can use double quotes? And please never redefine built-in identifiers like str.
@Wombatz sorry I have edit string name but it's a good practice to escape single-quote(') because it needs to be escaped if we use r' ' instead of r" "
If you use r" " you don't have to escape anything.

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.