Python将字符串与正则表达式匹配

Zac*_*ack 32 python regex

我需要一个python正则表达式来检查字符串中是否存在单词.该字符串可能以逗号分隔.

所以,例如,

line = 'This,is,a,sample,string'
Run Code Online (Sandbox Code Playgroud)

我想基于"样本"进行搜索,这将返回true.我很喜欢reg ex,所以当我查看python文档时,我看到了类似的内容

import re
re.match(r'sample', line)
Run Code Online (Sandbox Code Playgroud)

但我不知道为什么在文本匹配之前会有'r'.有人可以用正则表达式帮助我吗?

jab*_*edo 58

你确定你需要正则表达式吗?看来你只需要知道字符串中是否有单词,所以你可以这样做:

>>> line = 'This,is,a,sample,string'
>>> "sample" in line
 True
Run Code Online (Sandbox Code Playgroud)


iCo*_*dez 24

r使字符串原始的字符串,它不处理转义字符(但是,因为有没有在字符串中,实际上这里不需要它).

此外,re.match从字符串的开头匹配.换句话说,它寻找字符串和模式之间的精确匹配.要匹配字符串中任何位置的内容,请使用re.search.请参阅下面的演示:

>>> import re
>>> line = 'This,is,a,sample,string'
>>> re.match("sample", line)
>>> re.search("sample", line)
<_sre.SRE_Match object at 0x021D32C0>
>>>
Run Code Online (Sandbox Code Playgroud)


mln*_*nyc 7

r代表一个原始字符串,因此\像\将自动转义为\.

通常,如果你希望你的模式包含类似反斜杠的东西,你需要用另一个反斜杠来逃避它.原始字符串消除了这个问题

简短的解释

在你的情况下,它并不重要,但它是一个很好的习惯进入早期否则像\ b将会在后面咬你如果你不小心(将被解释为退格字符而不是字边界)

根据re.match vs re.search这里有一个例子,它将为您澄清:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>
Run Code Online (Sandbox Code Playgroud)

所以搜索会在任何地方找到匹配,匹配只会从头开始


Inb*_*ose 5

您不需要正则表达式来检查字符串中是否存在子字符串。

line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True
Run Code Online (Sandbox Code Playgroud)

如果您想知道字符串是否包含模式,那么您应该使用re.search

line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'
Run Code Online (Sandbox Code Playgroud)

这最好与模式匹配一​​起使用,例如:

line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'
Run Code Online (Sandbox Code Playgroud)