Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

regex - How to match exact "multiple" strings in Python

I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.

pat1 = re.compile('foo.tralingString')
mat1 = pat1.match(mystring)

pat2 = re.compile('bar.trailingString')
mat2 = pat2.match(mystring)

if mat1 or mat2:
    # Do whatever

pat = re.compile('[foo|bar].tralingString')
match = pat.match(mystring) # Doesn't work

The only condition is that I've got a list of strings which are to be matched exactly. Whats the best possible solution in Python.

EDIT: The search patterns have some trailing patterns common.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do a trivial regex that combines those two:

pat = re.compile('foo|bar')
if pat.match(mystring):
    # Do whatever

You could then expand the regex to do whatever you need to, using the | separator (which means or in regex syntax)

Edit: Based upon your recent edit, this should do it for you:

pat = re.compile('(foo|bar)\.trailingString');
if pat.match(mystring):
    # Do Whatever

The [] is a character class. So your [foo|bar] would match a string with one of the included characters (since there's no * or + or ? after the class). () is the enclosure for a sub-pattern.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...