匹配没有任何顺序的字符串子字符串

匹配没有任何顺序的字符串子字符串

问题描述:

有没有办法匹配没有任何顺序的字符串中的子字符串?匹配没有任何顺序的字符串子字符串

可以说我有一个字符串

Hello how are you doing you have a nice day hello there 

和我匹配的子字符串是“你好”,“你”。

现在我需要一个正则表达式模式将匹配hello how are youyou doing you(already matched shouldn't match again) have a nice day hello

我想是这样的,但没有工作

(hello|you)[\w\s]*?[^($1)](hello|you) 

预期输出:

Hello how are you 
you doing you have a nice day hello 
you have a nice day hello 

基本上我想匹配'你好...你'之间的任何东西,反之亦然'你好'

我不怎么摆脱第一个匹配模式。任何想法来解决这个问题?

更新时间:

基本上我的问题是我需要配合没有重复子串的字符串。在上面,句子是“你好,你怎么做你有一个愉快的一天你好”匹配字符串是“你好”,“你”,因此我需要匹配一个子字符串以hello开头,结束于你或从你开始与你好结束,而不是开始与你和你同样的方式与你好

+0

您的预期输出是什么? –

+0

我需要匹配的模式,将匹配以下, '你好,你好吗'和'你在做你有一个愉快的一天你好' – aswin

+0

所以基本上你想匹配'hello'和'你'之间的任何东西? –

从我从你的问题理解的结束,这可能是你想要的东西:

t = "Hello how are you doing you have a nice day hello there" 
pattern = ["(?=hello).*?(?<=you)","(?=you).*?(?<=hello)"] 
for p in pattern: 
    pat = re.compile(p) 
    for m in pat.finditer(t.lower()): 
    print m.group() 

输出是:

你好,你好吗
你在做你有一个愉快的一天hel罗

使用此模式与re.findall

(?si)(?=((?:hello|you).*?(?:hello|you))) 

regex demo

Python demo

import re 
p = re.compile(r'(?=((?:hello|you).*?(?:hello|you)))', re.IGNORECASE | re.DOTALL) 
test_str = "Hello how are you doing you have a nice day hello there" 
print(p.findall(test_str)) 
# => ['Hello how are you', 'you doing you', 'you have a nice day hello'] 

正则表达式的解释:

  • (?si) - 使DOTALL(.匹配换行符,太)和忽略大小写标志
  • (?=((?:hello|you).*?(?:hello|you))) - 正超前不消耗字符,但允许在re.findall所述字符串中的每个位置捕获子串。它搜索:
    • (?:hello|you) - 文字字符序列helloyou
    • .*? - 任何字符,0或多次出现,尽可能少
    • (?:hello|you) - 文字字符序列helloyou

仅匹配helloyou整个w您可以添加字边界\b

(?si)(?=(\b(?:hello|you)\b.*?\b(?:hello|you)\b)) 
     ^^    ^^ ^^    ^^ 
+0

感谢stribizhev的解释,但我的问题是如何避免'你在做你'。假设你已经匹配过一次,即(你)在做你,我们可以避免再次匹配'你'吗?这将避免你做你, – aswin

+0

基本上我的问题是我需要匹配没有重复的子字符串的字符串。在上面,句子是“你好,你怎么做你有一个愉快的一天你好”匹配字符串是“你好”,“你”,因此我需要匹配一个字符串与你好,结束与你或从你开始,结束于你好,不是从你开始,以你同样的方式与你结束 – aswin

+0

像[this](https://regex101.com/r/iP7iF0/3)? –