繁体   English   中英

Python Regex仅匹配每个单词大写的位置

[英]Python Regex match only where every word is capitalized

我想匹配所有单词都被限制的所有字符串。

目前我尝试过这样的事情:

list = ["This sentence should Not Match", "This Should Only Match"]
match = []
for l in list:
   x = re.search("^[A-Z]*.", l)
   if x:
      match.append(l)

例如,我希望正则表达式只匹配:“这是一个很好的例子在这里”,但它不应该匹配:“像这样的东西”,“这里是一个不应该匹配的例子”,“TiHiS SeNtEnEcE”或者“这不应该匹配.Foo”

我正在循环播放大量新闻文章并尝试匹配所有标题。 这些标题通常都是大写的。

你可以没有正则表达式:

l = ["This sentence should Not Match", "This Should Only Match"]
[s for s in l if s.istitle()]

输出:

['This Should Only Match']

尝试使用以下模式使用re.search进行匹配:

^[A-Z][a-z]*(?: [A-Z][a-z]*)*$

脚本:

list = ["This sentence should Not Match", "This Should Only Match"]
matches = []
for l in list:
    x = re.search("^[A-Z][a-z]*(?: [A-Z][a-z]*)*$", l)
    if x:
        matches.append(l)

print(matches)

这打印:

['This Should Only Match']

我首先支持Chris的解决方案,但这是一种可能的正则表达式方法:

import re

sentences = ["This sentence should Not Match", "This Should Only Match"]
result = [x for x in sentences if re.match(r"^([A-Z][a-z]*\b\s*)+$", x)]
print(result) # => ["This Should Only Match"]

正则表达式仅匹配具有一个或多个单个大写字母的字符串,后跟0或更多小写字母,单词边界和可选空格。

注意:尽量避免覆盖内置函数list()并且总是使正则表达式字符串原始是一个好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM