如果在字符串中找到另一个关键字,我正在尝试在 python 中使用正则表达式从大字符串中提取一个小子字符串。
例如-
s = "1 0001 1 UG science,ee;YEAR=onefour;standard->2;district->9"
if "year" in s:
print ("The year is = ",VALUE_OF_YEAR)<--- here I hope to somehow get the year substring from the above string and print it.
即答案看起来像
The year is = onefour
请注意 - 如果它表示不同的数字,如 onethree、oneseven 等,该值将会改变
我基本上想复制从之后开始的任何内容
=
直到
;
如果我找到了
YEAR
在字符串中打印出来
我不太确定该怎么做。
我尝试在 python 中使用字符串操作方法,但到目前为止我还没有找到任何方法来精确复制所有单词直到 ';'在字符串中。
任何帮助将不胜感激。也欢迎任何其他方法。
最佳答案
你也可以有一个saving group捕获 year
值:
>>> import re
>>>
>>> pattern = re.compile(r"YEAR=(\w+);")
>>> s = "1 0001 1 UG science,ee;YEAR=onefour;standard->2;district->9"
>>> pattern.search(s).group(1)
'onefour'
您可能还需要处理不匹配的情况。例如,返回 None
:
import re
def get_year_value(s):
pattern = re.compile(r"YEAR=(\w+);")
match = pattern.search(s)
return match.group(1) if match else None
关于python - 如果找到另一个关键字,则从 python 中的一行中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711122/