Python正则表达式查找独立案例

标签 python regex

例如,我有一串时间:

text = '2010; 04/20/2010; 04/2009'

我只想找到第一个独立的“2010”,但应用以下代码:

re.findall(r'\d{4}', text)

还会发现以 mm/dd/yyyy 格式嵌入的第二个“2010”。

有没有办法实现这一点(不使用“;”符号)?

最佳答案

您可以使用re.search仅查找第一个出现的位置:

>>> import re
>>> text = '2010; 04/20/2010; 04/2009'
>>> re.search('\d{4}', text)
<_sre.SRE_Match object; span=(0, 4), match='2010'>
>>> re.search('\d{4}', text).group()
'2010'
>>>

来自文档:

re.search(pattern, string, flags=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

强调我的。

关于Python正则表达式查找独立案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517690/

相关文章:

c# - 一系列数字的正则表达式和一个用于验证的字符

python - 在 Python Bokeh 图中选择字形

python - pystan .plot() 绘制跟踪摘要两次

regex - 为什么 REGEXEXTRACT 值相乘会返回不正确的结果?

javascript - 如何使用 Regex 将字符串中的所有数字四舍五入?

php - RegEx 用于匹配 CSS 文件中的特定 javaDoc 属性,并提取有关 css 定义的数据

python 2.3 - 删除目录而不等待进程完成

Python 名称重整与私有(private)继承

python - NetworkX 递归子节点

python - 如何使用python中的正则表达式提升两个分号之间的数据?