Python:在字符串中查找模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30358266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:19:19  来源:igfitidea点击:

Python: Find pattern in a string

pythonstring

提问by user3480774

I am trying to find a way to match a pattern p in a string s in python.

我试图找到一种方法来匹配 python 中字符串 s 中的模式 p。

s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'
# s, p -> a, z  # s and p can only be 'a' through 'z'

def match(s, p):
   if s matches p:
      return True
   else:
      return False

match(s, p) # return True
match(ss, p) # return True


I just tried:

我刚试过:

import re

s = "abccba"
f = "facebookgooglemsmsgooglefacebook"
p = "xyzzyx"

def fmatch(s, p):
    p = re.compile(p)
    m = p.match(s)
    if m:
        return True
    else:
        return False

print fmatch(s, p)
print fmatch(f, p)

Both return false; they are supposed to be true.

两者都返回false;他们应该是真的。

采纳答案by Stefan Pochmann

I convert your pattern into a regular expression that can then be used by re.match. For example, your xyzzyxbecomes (.+)(.+)(.+)\3\2\1$(the first occurrence of each letter becomes a capture group (.+), and subsequent occurences become the proper back reference).

我将您的模式转换为正则表达式,然后可以由re.match. 例如,您的xyzzyx变成(.+)(.+)(.+)\3\2\1$(每个字母的第一次出现成为一个捕获组(.+),随后出现的成为正确的反向引用)。

import re

s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'

def match(s, p):
    nr = {}
    regex = []
    for c in p:
        if c not in nr:
            regex.append('(.+)')
            nr[c] = len(nr) + 1
        else:
            regex.append('\%d' % nr[c])
    return bool(re.match(''.join(regex) + '$', s))

print(match(s, p))
print(match(ss, p))

回答by manglano

Compile a Python regular expressions object for some pattern of interest and then pass the string to its Match(string) method. You'll want to use a matchobject if you need a boolean output: https://docs.python.org/3/library/re.html#match-objects

为某些感兴趣的模式编译 Python 正则表达式对象,然后将字符串传递给它的 Match(string) 方法。match如果您需要布尔输出,则需要使用对象:https: //docs.python.org/3/library/re.html#match-objects

Example: Check string s for any word character (that is, alphanumerics)

示例:检查字符串 s 中是否有任何单词字符(即字母数字)

def match_string(s):
    ##compile a regex for word characters
    regex = re.compile("\w") 
    ##return the result of the match function on string 
    return re.match(s)

Hope it helps!

希望能帮助到你!

回答by Tenzin

You could make use of regular expressions.
Have a look here for some examples: Link

您可以使用正则表达式。
看看这里的一些例子:链接

I think you could use re.search()

我想你可以用 re.search()

Ecample:

营地:

import re 

stringA = 'dog cat mouse'
stringB = 'cat'

# Look if stringB is in stringA
match = re.search(stringB, stringA)

if match:
    print('Yes!')

回答by jatal

If I'm understanding your question, you're looking for a pythonic approach to pattern matching across a set of strings.

如果我理解你的问题,你正在寻找一种 pythonic 方法来跨一组字符串进行模式匹配。

Here is an example demonstrating the use of list comprehensions to achieve this goal.

这是一个示例,演示了使用列表理解来实现此目标。

I hope it helps you reach your goal. Please let me know if I can help further. - JL

我希望它能帮助你达到你的目标。如果我能提供进一步帮助,请告诉我。- JL

Demonstrate No Match Found

证明未找到匹配项

>>> import re
>>> s = ["abccba", "facebookgooglemsmsgooglefacebook"]
>>> p = "xyzzyx"
>>> result = [ re.search(p,str) for str in s ] 
>>> result
[None, None]

Demonstrate Combination of Matches and No Match in the result

在结果中展示匹配和不匹配的组合

>>> p = "abc"
>>> result = [ re.search(p,str) for str in s ] 
>>> result
[<_sre.SRE_Match object at 0x100470780>, None]
>>> [ m.group(0) if m is not None else 'No Match' for m in result ]
['abc', 'No Match']
>>> [ m.string if m is not None else 'No Match' for m in result ]
['abccba', 'No Match']

Demonstrate single statement

演示单条语句

>>> [ m.string if m is not None else 'No Match' for m in [re.search(p,str) for str in s] ]
['abccba', 'No Match']