我有一个字符串如下
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/