如何匹配 - 但不捕获 - 在 Python 正则表达式中? [英] How to match--but not capture--in Python regular expressions?

查看:46
本文介绍了如何匹配 - 但不捕获 - 在 Python 正则表达式中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数输出Washington D.C., DC, USA"作为输出.我需要拍摄华盛顿特区",原因与我如何处理该国其他每个城市有关.(注意:这与DC"相同,我需要在Washington"和DC"之间使用逗号,空格可以)

I've got a function spitting out "Washington D.C., DC, USA" as output. I need to capture "Washington, DC" for reasons that have to do with how I handle every single other city in the country. (Note: this is not the same as "D.C.", I need the comma to be between "Washington" and "DC", whitespace is fine)

我一生都无法弄清楚如何捕捉这个.

I can't for the life of me figure out how to capture this.

这是我尝试过的:

    >>>location = "Washington D.C., DC, USA"

    >>>match = re.search(r'\w+\s(?:D\.C\.), \w\w(?=\W)', location).group()
    >>>match
    u'Washington D.C., DC'

是不是 (?: ...) 应该只匹配(而不是捕获)DC"?

Is not (?: ...) supposed to just match (and not capture) "D.C."?

这里是 2.7.2 文档:

Here are the 2.7.2 Docs:

(?:...)常规括号的非捕获版本.匹配括号内的任何正则表达式,但组匹配的子字符串在执行匹配后无法检索或在模式后面引用.

(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

什么给了??

提前致谢!

推荐答案

这确实是一个聪明的方法,但不捕获并不意味着从匹配中删除它.这只是意味着,它不被视为输出组.

That's a clever way indeed, but not-capturing doesn't mean removing it from match. It just mean, that it's not considered as an output group.

您应该尝试执行以下类似操作:

You should try to do something similar to the following:

match = re.search(r'(\w+)\s(?:D\.C\.), (\w\w)\W', location).groups()

这会打印 ('Washington', 'DC').

注意 .group().groups() 之间的区别.前者为您提供匹配的整个字符串,后者仅提供捕获的组.请记住,您需要指定要在输出中包含的内容,而不是要排除的内容.

Note the difference between .group() and .groups(). The former gives you the whole string that was matched, the latter only the captured groups. Remember, you need to specify what you want to include in the output, not what you want to exclude.

这篇关于如何匹配 - 但不捕获 - 在 Python 正则表达式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆