Python使用子字符串在字符串中查找字符串

标签 python regex string

<分区>

我需要在包含子字符串的字符串中找到整个单词。

例如,如果 replacement 是一个字符串,我将搜索 replace ,那么它将匹配 replacement 并且它应该返回 replacement。

这是我尝试过的

>>> a = 'replacement replace  filereplace   filereplacer'
>>> re.findall(r'replace',a)

['replace', 'replace', 'replace', 'replace']

但我需要的是:

['replacement', 'replace', 'filereplace', 'filereplacer']

最佳答案

匹配单词边界和 \w(对标点符号也很稳健):

import re

a = 'replacement replace  filereplace,   filereplacer.  notmatched'
print(re.findall(r'\b\w*replace\w*\b',a))

结果:

['replacement', 'replace', 'filereplace', 'filereplacer']

关于Python使用子字符串在字符串中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921980/

相关文章:

python - Selenium 获取div后段落中的文本

java - 每两个字符后分割一个字符串

c++ - 使用表达式初始化 char * 不起作用

java - IPv6 验证

regex - 如何为 GIIN 格式验证创建正则表达式 VBA 宏

C++ 在构造函数中删除对象?

python - 如何更改主页上的特色群组/组织?

python - Swig,返回 double 数组

python - 从字符串末尾开始的非贪婪 Python 正则表达式

java - 正则表达式给出错误的结果