gpt4 book ai didi

python - 如何使单词边界\b 在破折号上不匹配

转载 作者:太空狗 更新时间:2023-10-29 22:25:15 24 4
gpt4 key购买 nike

我针对遇到的具体问题简化了代码。

import re
pattern = re.compile(r'\bword\b')
result = pattern.sub(lambda x: "match", "-word- word")

我得到了

'-match- match'

但是我想要

'-word- match'

编辑:

或者对于字符串"word -word-"

我要

"match -word-"

最佳答案

你需要的是消极的回顾。

pattern = re.compile(r'(?<!-)\bword\b')
result = pattern.sub(lambda x: "match", "-word- word")

引用documentation :

(?<!...) Matches if the current position in the string is not preceded by a match for ....

所以这只会匹配,如果分词 \b前面没有减号 - .

如果您需要在字符串末尾使用它,则必须使用如下所示的否定前瞻:(?!-) .完整的正则表达式将导致:(?<!-)\bword(?!-)\b

关于python - 如何使单词边界\b 在破折号上不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684942/

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