简体   繁体   English

正则表达式-用大写字母替换所有匹配项

[英]Regex - replace every matching occurrence with uppercase

How do I uppercase every matching occurrence? 如何将每个匹配的事件大写? Each two letter combo, first upper, second lower, where they are surrounded by a space or begin/end of string. 每两个字母组合,第一个大写字母,第二个小写字母,由空格或字符串的开头/结尾包围。

re.sub('( |^)[A-Z][a-z]($| )', lambda m: m.group(0).upper(), loc) 

works with 与...合作

loc = ' Ny' # or ' Ny ' or 'Ny '

but not 但不是

loc = ' Ny Us'

I'd like the results to be NY and NY US 我希望结果是NYNY US

I'm working in Python 2.7. 我正在使用Python 2.7。

You may convert the last group to a lookahead: 您可以将最后一组转换为前瞻:

re.sub('( |^)[A-Z][a-z](?=$| )', lambda m: m.group(0).upper(), loc)
                       ^^^^^^^

See the Python demo . 参见Python演示

The point is to allow the regex engine to match the space after the last letter that was matched at the previous iteration. 关键是允许正则表达式引擎在上次迭代中匹配的最后一个字母之后匹配空格。

Here is an alternative regex based on lookarounds that you may use for the same task: 这是基于您可以用于同一任务的环顾的替代正则表达式:

r'(?<!\S)[A-Z][a-z](?!\S)'

See this regex demo . 请参阅此正则表达式演示 The (?<!\\S) negative lookbehind requires the position at the start of a string or the one that is preceded with a whitespace. 后面的(?<!\\S)负数要求在字符串开头或在空格开头的位置。 The (?!\\S) negative lookahead requires the end of string position or a whitespace immediately to the right of the current location. (?!\\S)负前瞻需要字符串位置的末尾或紧接当前位置右侧的空格。

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

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