python - 使用正则表达式查找子字符串是否存在,如果是,则从 python 中的主字符串中分离出来

标签 python regex python-3.x substring

我有一个字符串如下

strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's)"

如果上面的字符串有年份子串(例如 2014、2015 等),则将 'year' 子串和其余部分分开。

获取我正在使用的“年份”

re.findall(r"\b20[012]\d\b",strng)

我怎样才能得到子字符串的其余部分。 预期输出是

year_substring --> '2018'
rest --> 'Fiscal Year Ended March 31, Total Year (in $000's)'

有什么方法可以使用正则表达式同时获得两者吗?

最佳答案

您可以捕获 3 部分,年份之前的字符串,年份和其余部分,然后连接第 1 组和第 3 组以获得其余部分:

import re
strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's)"
m = re.search(r"(.*)\b(20[012]\d)\b(.*)",strng)
if m:
    print("YEAR: {}".format(m.group(2)))
    print("REST: {}{}".format(m.group(1),m.group(3)))

参见 Python demo .输出:

YEAR: 2018
REST: Fiscal Year Ended March 31,  Total Year (in $000's)

如果您的字符串有多个匹配项,请将 re.split 与您的模式一起使用:

import re
strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's) and Another Fiscal Year Ended May 31, 2019 Total Year (in $000's)"
print(re.findall(r"\b20[012]\d\b",strng))
# => ['2018', '2019']
print(" ".join(re.split(r"\b20[012]\d\b",strng)))
# => Fiscal Year Ended March 31,   Total Year (in $000's) and Another Fiscal Year Ended May 31,   Total Year (in $000's)

参见 another Python demo .

您也可以使用 strip() 去除组的前导/尾随空格。

关于python - 使用正则表达式查找子字符串是否存在,如果是,则从 python 中的主字符串中分离出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667096/

相关文章:

sql - 正则表达式中 (*) 和 .* 有什么区别?

python - Bash 正在等待 python 子进程

python - 如何在没有numpy的情况下使用范围填充矩阵?

python - 合并两个列表并使用 python 中的分隔符相应地连接它们

python - 如何更新 Pandas 中的现有数据框?

python - 从 azure blob 存储中读取多行

python - python 中的 Bokeh 库 : can I provide a custom y range in terms of values to have?

python - 根据具有特殊条件的单词之间的逗号拆分字符串 - Python

php - 为什么 preg_match 返回一些空元素?

Django/Python 将字符串转换为模型过滤器,结果为 '='