使用regex查找存在的子字符串,如果是,则将if与python中的主字符串隔离

2024-09-29 05:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串如下

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

如果上面的字符串有一个年份子字符串(例如。。20142015等),将“年”子串和其他子串分开。你知道吗

为了得到我用的“年”

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

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

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

有没有办法用regex把这两个都用上?你知道吗


Tags: 字符串inresubstringyeartotalfiscal年份
1条回答
网友
1楼 · 发布于 2024-09-29 05:27:34

您可以捕获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()从前导/尾随空格中去除组。你知道吗

相关问题 更多 >