繁体   English   中英

Python如何在字符串中查找子字符串并打印包含子字符串的整个字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM