gpt4 book ai didi

python - 正则表达式选择整行

转载 作者:行者123 更新时间:2023-12-02 02:15:41 25 4
gpt4 key购买 nike

我想使用正则表达式捕获文本字符串中的所有行。我怎么做?这些都不起作用。第一个几乎可以工作,但没有捕获\r\n

import re

given_text = '1stline\n2ndline\r3rdline\r\n4thline'
list_of_lines = re.findall('(?m)^.*$', given_text)
print(list_of_lines)

list_of_lines = re.findall('(?m)^.*(\r\n|\r|\n|$)', given_text)
print(list_of_lines)

list_of_lines = re.findall(r'(?m)^.*?(\r\n|\r|\n|$)', given_text)
print(list_of_lines)

最佳答案

当然splitlines()是完成这项工作的正确工具。

如果您只需要处理 CR,\r,以下解决方案可能会有所帮助。 (回车)和 LF,\n (换行符):

re.findall('[^\r\n]+', given_text) # Returns all non-empty lines split with one or more CR/LF chars
re.split(r'\r\n?|\n', given_text) # Splits with the most common CRLF, CR or LF line endings

注意 re.split 解决方案也会返回空行。

详细信息

  • [^\r\n]+ - 除 CR 和 LF 字符之外的一个或多个字符
  • \r\n?|\n - CR 和可选的 LF 字符 ( \r\n? ) 或 ( | ) 换行符、LF,仅 ( \n )

如果需要支持所有可能的Unicode换行符,可以使用

re.findall(r'[^\r\n\x0B\x0C\x85\u2028\u2029]+', given_text)
re.split(r'\r\n?|[\n\x0B\x0C\x85\u2028\u2029]', given_text)

注释:

<表类=“s-表”><标题>字符描述 <正文> \r (\x0D) 回车符,CR \n (\x0A) 换行,换行 \x0B 行制表,LT \x0C 换页,FF ‎\x85 下一行,NEL \u‎2028 行分隔符,LS \u‎2029 段落分隔符,PS

查看Python demo :

import re
given_text = '1stline\n2ndline\r3rdline\r\n4thline\r\n\r\nLast Line after an empty line'
print( re.findall('[^\r\n]+', given_text) )
# => ['1stline', '2ndline', '3rdline', '4thline', 'Last Line after an empty line']
print( re.split(r'\r\n?|\n', given_text) )
# => ['1stline', '2ndline', '3rdline', '4thline', '', 'Last Line after an empty line']
print( re.findall(r'[^\r\n\x0B\x0C\x85\u2028\u2029]+', given_text) )
# => ['1stline', '2ndline', '3rdline', '4thline', 'Last Line after an empty line']
print( re.split(r'\r\n?|[\n\x0B\x0C\x85\u2028\u2029]', given_text) )
# => ['1stline', '2ndline', '3rdline', '4thline', '', 'Last Line after an empty line']

关于python - 正则表达式选择整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67219133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com