简体   繁体   中英

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())

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM