本文介绍了如何匹配精确的“多个"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

唯一的条件是我有一个要精确匹配的字符串列表.Python 中最好的解决方案是什么.

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.

搜索模式有一些常见的尾随模式.

The search patterns have some trailing patterns common.

推荐答案

你可以做一个简单的正则表达式,将这两者结合起来:

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)

根据您最近的编辑,这应该适合您:

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

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

[] 是一个字符类.因此,您的 [foo|bar] 将匹配一个带有 one 包含字符的字符串(因为类之后没有 * 或 + 或 ? ).() 是子模式的外壳.

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.

这篇关于如何匹配精确的“多个"Python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:53