Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式在具有特定规则的字符串中查找子字符串?_Python_Regex_String - Fatal编程技术网

Python 如何使用正则表达式在具有特定规则的字符串中查找子字符串?

Python 如何使用正则表达式在具有特定规则的字符串中查找子字符串?,python,regex,string,Python,Regex,String,我有一根像下面这样的线 Hello there how are you? 我想在字符串中查找子字符串'there how'。所以我会这样做 import re string = "Hello there how are you?" term = "there how" print(re.search("\s" + term + "\s", string).group(0)). # /s is used to ensure the match should be an independent

我有一根像下面这样的线

Hello there how are you?
我想在字符串中查找子字符串
'there how'
。所以我会这样做

import re
string = "Hello there how are you?"
term = "there how"
print(re.search("\s" + term + "\s",  string).group(0)). # /s is used to ensure the match should be an independent phrase
但现在的问题是,如果我得到字符串的一个变体,那么匹配就不会发生。例如,对于这样的字符串

如果单词之间有很大的空格

Hello there         how are you?
如果某些字母大写

Hello There How are you?
我想做的是确保只要子字符串
'there how'
作为一个单独的短语出现在字符串中(不像
Hellothere how are you?
Hello there how are you?
等),我就应该能够找到匹配项


如何实现该目标?

您可以在
术语中用
\s+
替换空格,并通过传递
re.I
标志使用不区分大小写的匹配:

import re
ss = ["Hello there how are you?", "Hello there         how are you?", "Hello There How are you?"]
term = "there how"
rx = re.compile(r"(?<!\S){}(?!\S)".format(term.replace(r" ", r"\s+")), re.I)

for s in ss:
    m = re.search(rx,  s)
    if m:
        print(m.group())

注意:如果
术语
可以包含特殊的正则表达式元字符,则需要
重新转义
术语
,但在将空格替换为
\s+
之前要这样做。由于空格是用
re.escape
转义的,因此需要
替换(r'\',r'\s+)


rx=re.compile(r)(?@Wikton哇!这个解决方案可以处理各种变化。谢谢!嘿,很抱歉打扰你,但我的团队希望用javascript实现。基本上,用户只需按下一个按钮,然后就必须进行检查。你知道如何用javascript实现你的解决方案吗?这对我有很大帮助。你想让我创建一个单独的解决方案吗提问并标记你在那里?@SouvikRay请检查JS解决方案。这只是一个演示,其余的你需要自己实现。
there how
there         how
There How
rx = re.compile(r"(?<!\S){}(?!\S)".format(re.escape(term).replace(r"\ ", r"\s+")), re.I)