smilelife
smilelife

Reputation: 195

Regexp python - finding substring

How could I find all instances of a substring in a string?

For example I have the string ("%1 is going to the %2 with %3"). I need to extract all placeholders in this string (%1, %2, %3)

The current code could only find the first two because the ending is not a white space.

import re
string = "%1 is going to the %2 with %3"


r = re.compile('%(.*?) ')
m = r.finditer(string)
for y in m:
 print (y.group())

Upvotes: 1

Views: 212

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121216

Don't match on whitespace, match on a word boundary instead using \b:

r = re.compile(r'%(.*?)\b')

You may want to restrict your characters to word characters only instead of the . wildcard, and match at least one character:

r = re.compile(r'%(\w+)\b')

You don't appear to be using the capturing group either, so you could just omit that:

r = re.compile(r'%\w+\b')

Upvotes: 5

Related Questions