gpt4 book ai didi

Python RegEx 在单词前停止

转载 作者:行者123 更新时间:2023-11-28 21:47:22 29 4
gpt4 key购买 nike

我有一些正则表达式,我想弄明白:( of [A-Za-z ]+)?

我的正则表达式的上述部分将匹配以下内容:

of New Mexico and Mrs Smith.

我想做的是让 RegEx 在 之前停止。

( of [A-Za-z ]+)\sand?

上面的 RegEx 非常接近于解决问题,但它仍然匹配 and。

以上匹配:

of New Mexico and

我希望它输出:

of New Mexico

最佳答案

您可以使用 tempered greedy token :

( of (?:(?!\band\b)[A-Za-z ])+)?
^^^^^^^^^^^^^^^^^^^^^^^^^

参见 regex demo

(?:(?!\band\b)[A-Za-z ])+ 构造匹配 [A-Za-z ]< 中定义的 1+ 个字符 不是整个单词 的字符类。

Python demo :

import re
p = re.compile(r'( of (?:(?!\band\b)[A-Za-z ])+)?')
s = " of New Mexico and Mrs Smith."
m = p.search(s)
if m:
print(m.group().strip())

关于Python RegEx 在单词前停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599494/

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