gpt4 book ai didi

python - ?= 和 ?P 组合在正则表达式中

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:32 34 4
gpt4 key购买 nike

简而言之:我想使用Lookahead Python 中的技术 ?P<name>约定(详细信息 here )按名称获取组。

更多详细信息:

我发现了 Lookahead 技巧 here ;例如以下正则表达式...

/^(?=.*Tim)(?=.*stupid).+

... 允许检测类似 "Tim stupid" 的字符串或"stupid Tim" ,顺序并不重要。

我不知道如何组合 ?= “运算符”为 ?P一;下面的正则表达式显然并不能解决问题,但给出了我想要的想法:

/^(?=?P<word1>.*Tim)(?=?P<word2>.*stupid).+

最佳答案

?P<word1>在你的正则表达式中提醒 named capture group :

The syntax for a named group is one of the Python-specific extensions: (?P<name>...). *name* is, obviously, the name of the group. Named groups also behave exactly like capturing groups, and additionally associate a name with a group.

因此,您很可能正在寻找一种方法来捕获在开始处锚定的正前瞻内的子字符串,以要求字符串满足两种模式,并捕获两个前瞻内的子字符串:

^(?=(?P<word1>.*Tim))(?=(?P<word2>.*stupid)).+
^^^^^^^^^^ ^ ^^^^^^^^^^ ^

请参阅regex demo

请注意,如果您不需要字符串本身,.+是多余的,可以删除。如有必要,您可能需要重新调整命名捕获组的边框。

关于python - ?= 和 ?P 组合在正则表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164433/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com