\b(keyword)\n(\w+)\b
\b get a word boundary
(keyword) capture keyword (replace with whatever you want)
\n match a newline
(\w+) capture some word characters, one or more
\b get a word boundary
If you wish to explore/simplify/modify the expression, it's been
explained on the top right panel of
regex101.com. If you'd like, you
can also watch in this
link, how it would match
against some sample inputs.
import re
regex = r"(?<!\S)(keyword)[\t ]*\r?\n[\t ]*(\w+)(?!\S)"
test_str = (" This is my keyword\n"
" value")
matches = re.search(regex, test_str)
if matches:
print('{} {}'.format(matches.group(1), matches.group(2)))
那
\b(keyword)\n(\w+)\b
呢?你知道吗因为
keyword
和\w+
在捕获组中,您可以在以后的代码中根据需要引用它们。你知道吗Try it here!
我的猜测是,根据新行的数量,一个表达式类似于:
可能有点接近并且
value
在\2
中,您可以使第一个组不被捕获,然后:\1
是value
。你知道吗您可以匹配关键字(或者使用alternation)来匹配更多的关键字,并在关键字之后和匹配换行符之后考虑尾部制表符和空格。你知道吗
按照您尝试的模式使用2个捕获组:
解释
(?<!\S)
负的lookback,断言直接在左边的不是非空格字符(keyword)
在组1中捕获匹配关键字的[\t ]*
匹配0+个制表符或空格\r?\n
匹配换行符[\t ]*
匹配0+个制表符或空格(\w+)
捕获第2组匹配1+个单词字符(?!\S)
负向前看,断言直接在右边的不是非空格字符Regex demo| Python demo
例如:
输出
相关问题 更多 >
编程相关推荐