![](/img/trans.png)
[英]Python: How can I use a regex to split sentences to new lines, and then separate punctuation from words using whitespace?
[英]Regex: split new lines between constant words
给定
Word1 content1 content1 content1
content2 content2 content2
content3 content3 content3
Word2
我想将 content1、content2 和 content3 提取为组。 你能帮忙做一个正则表达式吗? 我试过了:
Word1[\s:]*((?P<value>[^\n]+)\n)+Word2
带有 gms 标志,但它没有帮助。 我需要 python re 模块的正则表达式。
您可以使用
import re
text = "Word1 content1 content1 content1\n content2 content2 content2\n content3 content3 content3\nWord2"
match = re.search(r'Word1[\s:]*((?:.+\n)*)Word2', text)
if match:
print([s.strip() for s in match.group(1).splitlines()])
输出:
['content1 content1 content1', 'content2 content2 content2', 'content3 content3 content3']
详情:
Word1
- Word1
字符串[\s:]*
- 零个或多个空格和冒号((?:.+\n)*)
- 第 1 组:除换行符以外的一个或多个字符的零次或多次重复,后跟换行符Word2
- Word2
字符串。 然后,如果有匹配项, [s.strip() for s in match.group(1).splitlines()]
将 Group 1 值拆分为单独的行。
使用PyPi 正则表达式库的替代解决方案可以是
import regex
text = "Word1 content1 content1 content1\n content2 content2 content2\n content3 content3 content3\nWord2"
print( regex.findall(r'(?<=Word1[\s:]*(?s:.*?))\S(?:.*\S)?(?=(?s:.*?)\nWord2)', text) )
请参阅Python 演示。 详情:
(?<=Word1[\s:]*(?s:.*?))
- 需要一个Word1
字符串、零个或多个空格或冒号,然后是尽可能少的零个或多个字符当前位置的左侧\S(?:.*\S)?
- 一个非空白字符,然后是除换行符之外的任何零个或多个字符,直到行上的最后一个非空白字符(?=(?s:.*?)\nWord2)
- 一个正向前瞻,需要尽可能少的零个或多个字符,然后在当前位置右侧添加一个换行符和Word2
字。更好地提取以将 2 个单词之间的所有内容分组,然后用换行符将其拆分。
first_key = "Word1"
second_key = "Word2"
common_regex = r"{first_key}[\s:]*(?P<value>.+){second_key}"
regex = common_regex.format(first_key=first_key, second_key=second_key)
lines = [x.group("value").strip() for x in re.finditer(regex, text_piece, re.DOTALL)]
if lines:
lines = lines[0].split("\n")
else:
lines = []
print(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.