[英]Python: Find pattern in a string
我試圖找到一種方法來匹配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
我剛嘗試過:
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)
兩者都歸零; 他們應該是真的。
我將您的模式轉換為正則表達式,然后由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))
如果我理解你的問題,那么你正在尋找一種pythonic方法來對一組字符串進行模式匹配。
這是一個示例,演示了使用列表推導來實現這一目標。
我希望它可以幫助您實現目標。 如果我能進一步幫助,請告訴我。 - JL
證明找不到匹配
>>> import re
>>> s = ["abccba", "facebookgooglemsmsgooglefacebook"]
>>> p = "xyzzyx"
>>> result = [ re.search(p,str) for str in s ]
>>> result
[None, None]
在結果中展示匹配和不匹配的組合
>>> 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']
展示單一陳述
>>> [ m.string if m is not None else 'No Match' for m in [re.search(p,str) for str in s] ]
['abccba', 'No Match']
為某些感興趣的模式編譯Python正則表達式對象,然后將該字符串傳遞給其Match(string)方法。 如果需要布爾輸出,則需要使用match
對象: https : //docs.python.org/3/library/re.html#match-objects
示例:檢查字符串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)
希望能幫助到你!
您可以使用正則表達式。
看看這里的一些例子: 鏈接
我想你可以使用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!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.