匹配没有任何顺序的字符串子字符串
问题描述:
有没有办法匹配没有任何顺序的字符串中的子字符串?匹配没有任何顺序的字符串子字符串
可以说我有一个字符串
Hello how are you doing you have a nice day hello there
和我匹配的子字符串是“你好”,“你”。
现在我需要一个正则表达式模式将匹配hello how are you
和you 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开头,结束于你或从你开始与你好结束,而不是开始与你和你同样的方式与你好
答
从我从你的问题理解的结束,这可能是你想要的东西:
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)))
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)
- 文字字符序列hello
或you
-
.*?
- 任何字符,0或多次出现,尽可能少 -
(?:hello|you)
- 文字字符序列hello
或you
-
仅匹配hello
和you
整个w您可以添加字边界\b
:
(?si)(?=(\b(?:hello|you)\b.*?\b(?:hello|you)\b))
^^ ^^ ^^ ^^
您的预期输出是什么? –
我需要匹配的模式,将匹配以下, '你好,你好吗'和'你在做你有一个愉快的一天你好' – aswin
所以基本上你想匹配'hello'和'你'之间的任何东西? –