[英]Regex pattern for string - python
我想以这种格式对字符串进行分组:
Some_text Some_text 1 2 3
BEGIN Some_text Some_text
44 76 1321
Some_text Some_text
END Some_text
Some_Text Some_text 1 4 5
我想将它从BEGIN分组到END ,如下所示:
Some_text Some_text 1 2 3
<!-- START -->
BEGIN Some_text Some_text
44 76 1321
Some_text Some_text
END <!-- END --> Some_text
Some_Text Some_text 1 4 5
<!-- START -->
和<!-- END -->
- 这只是对分组开始和结束的注释。 我只想获取 BEGIN 和 END 之间的文本
我有类似的东西,但它不适用于每种情况 - 当有很多数据时,它就不起作用:
reg = re.compile(rf"{begin}[\-\s]+(.*)\n{end}", re.DOTALL)
core = re.search(reg, text).group(1)
lines = core.split("\n")
text是我的字符串,然后在分组后将其交换为列表 - 我不知道如何直接从列表中制作此正则表达式,然后我不必在字符串文本上执行此操作,而是在 python 列表文本上执行
给我一些提示或帮助我如何解决它。
示例代码:
import re
text="Some_text Some_text 1 2 3\nBEGIN Some_text Some_text\n44 76 1321\nSome_text Some_text\nEND Some_text\nSome_Text Some_text 1 4 5"
begin = "BEGIN"
end = "END"
reg = re.compile(rf"{begin}[\-\s]+(.*)\n{end}", re.DOTALL)
core = re.search(reg, text).group(1)
lines = core.split("\n")
print(lines)
它有效,但我不知道为什么有时它不会,当它需要大量文本时,例如:20k 个单词我只想获取BEGIN和END之间的文本
你可能会使用
^BEGIN\b(.*(?:\r?\n(?!(?:BEGIN|END)\b).*)*)\r?\nEND
如果要包含 BEGIN 和 END,可以省略捕获组
^BEGIN\b.*(?:\r?\n(?!(?:BEGIN|END)\b).*)*\r?\nEND
代码示例
import re
regex = r"^BEGIN\b(.*(?:\r?\n(?!(?:BEGIN|END)\b).*)*)\r?\nEND"
test_str = ("Some_text Some_text 1 2 3\n"
"BEGIN Some_text Some_text\n"
"44 76 1321\n"
"Some_text Some_text\n"
"END Some_text\n"
"Some_Text Some_text 1 4 5\n")
print(re.findall(regex, test_str, re.MULTILINE))
Output
[' Some_text Some_text\n44 76 1321\nSome_text Some_text']
这有效:
txt='''\
Some_text Some_text 1 2 3
BEGIN Some_text Some_text
44 76 1321
Some_text Some_text
END Some_text
Some_Text Some_text 1 4 5'''
import re
print(re.sub(r'(?=BEGIN )(.*END)',r'<!-- START -->\n\1 <!-- END -->',txt,flags=re.S))
或者,
print(re.sub(r'(?=^BEGIN )([\s\S]*END)',r'<!-- START -->\n\1 <!-- END -->',txt, flags=re.M))
要么打印:
Some_text Some_text 1 2 3
<!-- START -->
BEGIN Some_text Some_text
44 76 1321
Some_text Some_text
END <!-- END --> Some_text
Some_Text Some_text 1 4 5
这使用非贪婪模式来匹配从开始标记到结束标记的所有内容,包括标记。 正则表达式模式中的\b
是为了确保 BEGIN 和 END 不是较长单词的一部分,例如,“BEGIN”不会匹配“BEGINS”或“BEGINNING”。 注意:对于标记不匹配的输入,它可能无法正常工作,例如“ab c BEGIN de BEGIN 1 2 END 3”(两个 BEGIN)。
import re
txt='''\
Some_text Some_text 1 2 3
BEGIN Some_text Some_text
44 76 1321
Some_text Some_text
END Some_text
Some_Text Some_text 1 4 5'''
begin = 'BEGIN'
end = 'END'
regex = re.compile(rf"(?<=\b{begin}\b)(.*?)(?=\b{end}\b)", flags=re.DOTALL)
match = regex.search(txt)
if match:
print(match[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.