[英]Regex to match a particular word followed by another, along with a boundary identifier
我在Python中进行正则表达式匹配。 我试图遵循一些组合,但没有工作。 我是正则表达式的新手。 我的问题是,我有一个字符串如下。
string = ''' World is moving towards a particular point'''
我想要一个解决方案来检查单词“moving”之后是否存在单词“towards”,如果是,我想选择该行的其余部分(在'towards'之后),直到它以'。'结尾。 或' - '。 我是新手。 请提供一些好的建议。
就像是
re.findall (r'(?<=moving towards )[^-.]*', string)
['a particular point']
(?<=moving towards )
看看断言背后。 断言字符串先于moving towards
[^-.]*
匹配除-
或-
之外的任何内容.
它是如何匹配的
World is moving towards a particular point
|
(?<=moving towards ) #checks if this position is presceded by moving towards
#yes, hence proceeds with the rest of the regex pattern
World is moving towards a particular point
|
[^-.]
World is moving towards a particular point
|
[^-.]
# and so on
World is moving towards a particular point
|
[^-.]
你需要使用负面看 。 但是当你拥有它时它会起作用.
或者-
如果你还没有,你可以使用@ nu11p01n73R的答案。 :
>>> string = ''' World is moving towards a particular point.'''
>>> re.search(r'(?<=moving towards).*(?=\.|-)',string).group(0)
' a particular point'
(?<=moving towards).*
为负时向后看后匹配所有(。*) moving towards
和(?=\\.|-)'
是与之前所有匹配的负面后视( \\.|-
),这意味着.
或-
import re
str = ''' World is moving towards a particular point'''
match = re.search('moving towards\s+([^.-]+)', str)
if match:
var = match.group(1)
Output >>> a particular point
正则表达式调试链接
https://www.regex101.com/r/wV7iC7/1
要重复这个问题,你想检查在给定的string
是否有“moving”字样后跟“朝向”。 以下是使用parse模块执行此操作的方法:
import parse
string = "World is moving towards a particular point"
fmt = "moving {:w}"
result = parse.search(fmt, string)
assert result[0] == "towards"
请注意:w
格式规范会使结果与字母和下划线匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.