Python用正则表达式匹配一个字符串 [英] Python match a string with regex
问题描述
我需要一个 python 正则表达式来检查字符串中是否存在一个单词.字符串可能用逗号分隔.
例如,
line = 'This,is,a,sample,string'
我想根据样本"进行搜索,这将返回 true.我对 reg ex 很蹩脚,所以当我查看 python 文档时,我看到了类似
导入重新re.match(r'sample', line)
但我不知道为什么要匹配的文本前有一个r".有人可以帮我处理正则表达式吗?
您确定需要正则表达式吗?看来你只需要知道一个词是否出现在一个字符串中,所以你可以这样做:
<预><代码>>>>line = 'This,is,a,sample,string'>>>在线样品"真的I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially.
So for example,
line = 'This,is,a,sample,string'
I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw something like
import re
re.match(r'sample', line)
But I don't know why there was an 'r' before the text to be matched. Can someone help me with the regular expression?
Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:
>>> line = 'This,is,a,sample,string'
>>> "sample" in line
True
这篇关于Python用正则表达式匹配一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!