gpt4 book ai didi

python - 在正则表达式中编写可重复单词的简短版本的最佳方法| Python

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:23 25 4
gpt4 key购买 nike

我希望 a|b|c 的正则表达式重复多次,并用空格分隔,但正则表达式不应接受尾部空格:

 "a b c c b"  - ok
"a b c c b " - not ok

所以我有 "(a|b|c)( (a|b|c))+" 而不是 "((a|b|c) )+"但我的正则表达式有超过 3 个单词,因此模式很长且难以阅读。

"^((?:word1|word2|word3|word4|...)(?: (?:word1|word2|word3|word4|...))+)$"

我只想询问简短版本,使用前瞻/lookbehining机制来处理最后一个空格或类似于仅匹配内部空格的东西。 如何更改 ((a|b|c) )+ 来实现这一目标?

最佳答案

如果这些都是字母数字单词,那么您可以使用 word boundary anchors :

^(?:(?:word1|word2|word3|word4|...)\b\s*)+\b$

说明:

^      # Start of string
(?: # Start of non-capturing group, first matching...
(?:word1|word2|word3|word4|...) # ...one of these words,
\b # then matching the end of a word,
\s* # then matching zero or more whitespace
)+ # one or more times.
\b # At the end, make sure that the end of the last word...
$ # ...is at the end of the string.

第一个 \b 确保单词之间的 \s* 必须匹配至少一个空白字符。

关于python - 在正则表达式中编写可重复单词的简短版本的最佳方法| Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17785942/

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