[英]Python how to find a substring in a string and print the whole string containing the substring
我正在努力尋找打印包含特定子字符串的字符串的解決方案。 所以例如我有一個字符串
mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"
我想在上面的字符串中搜索"mon"
並打印"mon_this_is_monday"
但不知道該怎么做
我試着做
pattern = re.compile('mon_')
try:
match = re.search(pattern, mystr).group(0)
print(match)
except AttributeError:
print('No match')
但這只是將mon_
作為匹配的輸出。 如何將整個字符串"mon_this_is_monday"
作為輸出?
我們可以嘗試將re.findall
與模式\\b\\w*mon\\w*\\b
:
mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"
matches = re.findall(r'\b\w*mon\w*\b', mystr)
print(matches)
這打印:
['mon_this_is_monday']
正則表達式模式匹配:
\b a word boundary (i.e. the start of the word)
\w* zero or more word characters (letters, numbers, or underscore)
mon the literal text 'mon'
\w* zero or more word characters, again
\b another word boundary (the end of the word)
print([string for string in mystr.split(" ") if "mon" in string])
你也可以搜索正則表達式
import re
mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"
abc = re.search(r"\b(\w*mon\w*)\b",mystr)
print(abc.group(0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.