![](/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.