[英]Python regex match two string at two different order?
I want to match aaa bbb
and bbb aaa
in the following string: 我想在以下字符串中匹配
aaa bbb
和bbb aaa
:
aaa bbb bbb aaa
using 运用
match = re.search("^(?=.*(aaa))(?=.*?(bbb)).*$", subject, re.DOTALL | re.IGNORECASE)
see https://www.regex101.com/r/vA0nB0/2 请参阅https://www.regex101.com/r/vA0nB0/2
But it only match aaa bbb
. 但它只匹配
aaa bbb
。
How can I match bbb aaa
too? 我怎么能匹配
bbb aaa
?
If Python supports conditionals: 如果Python支持条件:
For out of order stuff, just use a conditional. 对于无序的东西,只需使用条件。
Note - change the quantifier in the group to reflect how many items 注意 - 更改组中的量词以反映有多少项
are required to match. 需要匹配。 Below shows
{2}
which requires both items somewhere. 下面显示了
{2}
,它需要两个项目。
You could change it to {1,}
- at least 1, or +
- same thing. 您可以将其更改为
{1,}
- 至少为1,或+
- 同样的事情。
(?:.*?(?:((?(1)(?!))aaa.*?bbb)|((?(2)(?!))bbb.*?aaa))){2}
(?:
.*?
(?:
( # (1)
(?(1)
(?!)
)
aaa .*? bbb
)
| ( # (2)
(?(2)
(?!)
)
bbb .*? aaa
)
)
){2}
Output: 输出:
** Grp 0 - ( pos 0 , len 21 )
aaa bbb bbb aaa
** Grp 1 - ( pos 0 , len 8 )
aaa bbb
** Grp 2 - ( pos 11 , len 10 )
bbb aaa
You could try the below simple regex. 您可以尝试以下简单的正则表达式。
>>> import re
>>> s = 'aaa bbb bbb aaa'
>>> re.findall(r'aaa.*?bbb|bbb.*?aaa', s)
['aaa bbb', 'bbb aaa']
How about something like this, if you know that its always going to be aaa
or bbb
? 如果你知道它总是
aaa
或bbb
,那么这样的事情怎么样?
>>> a = 'aaa bbb bbb aaa'
>>> match = re.findall("(aaa|bbb).+?(aaa|bbb)", a, re.DOTALL | re.IGNORECASE)
>>> match
[('aaa', 'bbb'), ('bbb', 'aaa')]
Here is the regex101 link : https://www.regex101.com/r/qO3uD3/1 这是regex101链接: https ://www.regex101.com/r/qO3uD3/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.