python - 如果找到另一个关键字,则从 python 中的一行中提取子字符串

标签 python regex string

如果在字符串中找到另一个关键字,我正在尝试在 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/

相关文章:

python - re.split 没有给出正则表达式的最后一个字符

java - 我如何剖析或分析这个正则表达式?

python - 在 Python 3.x 中从字符串中删除空格

regex - Powershell重命名文件删除从正则表达式子字符串开始的部分

c - 为什么 fgets() 和 strncmp() 在此 C 代码中无法用于字符串比较?

python - 在 python 3.5 中构建位字符串时出错 : the datatype is being set to U32 without my control

python - OnevsrestClassifier 和随机森林

python - 将一维列表转换为二维列表(写入错误)

python - 向 Dask 分布式集群提交任务时本地 python 文件导入问题

c# - 正则表达式脑抽筋 - 匹配 "foreign"但不匹配 "foreign key"