[英]RE to extract middle of line with or without a particuar word on the end
我试图在行的中间提取一个字符串,末尾有或没有特定单词。 例如,这一行:
START - some words and not THIS
应该返回“一些词而不是”,同样,该行:
START - some words and not
也应该返回相同的字符串。 我已经尝试使用我发现的 EOL 交替的示例中的前瞻,但是添加交替会返回一个以 THIS 结尾的字符串。 这是python正则表达式:
[^-]*- (.+(?= THIS|$))
删除 |$ 有效,除非行结束时没有 THIS。 我正在解析的数据有少量条目缺少“THIS”,因此我需要将两者都考虑在内。 什么是正确的模式?
请看看这个。
根据您的示例,以下正则表达式(?<=START - )(.*)(?=THIS)
将捕获some words and not
。 希望它会有所帮助!
如果我理解正确,这应该可以解决问题:
>>> regex = re.compile(r"(?!THIS)([^-]*- .+)(THIS)?$")
>>> s1 = 'START - some words and not THIS'
>>> regex.match(s1).groups()
('START - some words and not ', 'THIS')
>>> s2 = 'START - some words and not '
>>> regex.match(s2).groups()
('START - some words and not ', None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.