regex - Python - 检查字符串是否在更大的字符串中

标签 regex python-2.7

我正在使用 Python v2.7,我想知道您是否可以判断一个单词是否在字符串中。

例如,如果我有一个字符串和我想查找的单词:

str = "ask and asked, ask are different ask. ask"
word = "ask"

我应该如何编码,以便我知道我获得的结果不包含属于其他单词的单词。在上面的例子中,除了“asked”之外,我想要所有的“ask”。

我已尝试使用以下代码,但它不起作用:
def exact_Match(str1, word):
    match = re.findall(r"\\b" + word + "\\b",str1, re.I)
    if len(match) > 0:
        return True
    return False 

有人可以解释一下我该怎么做吗?

最佳答案

您可以使用以下功能:

>>> test_str = "ask and asked, ask are different ask. ask"
>>> word = "ask"

>>> def finder(s,w):
...   return re.findall(r'\b{}\b'.format(w),s,re.U)
... 
>>> finder(text_str,word)
['ask', 'ask', 'ask', 'ask']

请注意,您需要 \b对于边界正则表达式!

或者您可以使用以下函数返回 words 的索引:
在拆分字符串中:
>>> def finder(s,w):
...   return [i for i,j in enumerate(re.findall(r'\b\w+\b',s,re.U)) if j==w]
... 
>>> finder(test_str,word)
[0, 3, 6, 7]

关于regex - Python - 检查字符串是否在更大的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918227/

相关文章:

java - 使用正则表达式以任何顺序查找单词列表的子段

Python 正则表达式问题 : stripping multi-line comments but maintaining a line break

python - 为什么 "Broken pipe"只有在多进程的特定场景下访问共享列表时才会出现?

python - 如何找到 pandas 中每一对后续 DataFrame.index 值之间的差异?

python - 是否可以将范围作为变量 "var = k:k+number"

java - 如何使用模式/过滤器从目录中获取文件

regex - 什么时候对于正则表达式来说问题太复杂了?

php - 如何用正则表达式匹配 400 到 550 之间的数字?

python - Unicode(西里尔文)字符索引,用 python 重写

python - 当 stdin 包含 unicode 时,Popen 子进程不退出