gpt4 book ai didi

python - 正则表达式匹配引号中仅包含 3 个或更少大写单词的字符串

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

我搜索了又搜索,但找不到任何可以缓解我的正则表达式问题的方法。

我写了以下虚拟句子:

Watch Joe Smith Jr. and Saul "Canelo" Alvarez fight Oscar de la Hoya and Genaddy Triple-G Golovkin for the WBO belt GGG. Canelo Alvarez and Floyd 'Money' Mayweather fight in Atlantic City, New Jersey. Conor MacGregor will be there along with Adonis Superman Stevenson and Mr. Sugar Ray Robinson. "Here Goes a String". 'Money Mayweather'. "this is not a-string", "this is not A string", "This IS a" "Three Word String".

我正在寻找一个在 Python 3.6 中使用时将返回以下内容的正则表达式:

Canelo, Money, Money Mayweather, Three Word String

最接近我的正则表达式是:

(["'])[A-Z](\\?.)*?\1

我希望它只匹配由单引号或双引号括起来的 3 个或更少大写单词的字符串。不幸的是,到目前为止它似乎可以匹配引号中的任何字符串,无论长度如何,无论内容如何,​​只要它以大写字母开头即可。

我花了很多时间尝试自己破解它,但我碰壁了。谁能告诉我哪里出了问题?

最佳答案

尝试使用这个:(["'])((?:[A-Z][a-z]+ ?){1,3})\1

(["']) - 开场白

([A-Z][a-z]+ ?){1,3} - 大写单词重复 1 到 3 次,以空格分隔

[A-Z] - capital char (word begining char)

[a-z]+ - non-capital chars (end of word)

_? - space separator of capitalized words (_ is a space), ? for single word w/o ending space

{1,3} - 1 to 3 times

\1 - 收盘价,与开盘价相同

第 2 组 是您想要的。

Match 1
Full match 29-37 `"Canelo"`
Group 1. 29-30 `"`
Group 2. 30-36 `Canelo`
Match 2
Full match 146-153 `'Money'`
Group 1. 146-147 `'`
Group 2. 147-152 `Money`
Match 3
Full match 318-336 `'Money Mayweather'`
Group 1. 318-319 `'`
Group 2. 319-335 `Money Mayweather`
Match 4
Full match 398-417 `"Three Word String"`
Group 1. 398-399 `"`
Group 2. 399-416 `Three Word String`

RegEx101 演示:https://regex101.com/r/VMuVae/4

关于python - 正则表达式匹配引号中仅包含 3 个或更少大写单词的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44853048/

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