gpt4 book ai didi

python - 在python正则表达式中使用\r(回车)

转载 作者:行者123 更新时间:2023-12-04 16:23:08 25 4
gpt4 key购买 nike

我正在尝试使用正则表达式来匹配字符串和 \r 之间的每个字符特点 :

text = 'Some text\rText to find !\r other text\r'
我要配 'Text to find !' .我已经尝试过:
re.search(r'Some text\r(.*)\r', text).group(1)
但它给了我: 'Text to find !\r other text'令人惊讶的是,它在替换 \r 时完美运行来自 \n :
re.search(r'Some text\n(.*)\n', 'Some text\nText to find !\n other text\n').group(1)
返回 Text to find !你知道为什么当我们使用 \r 时它的行为会有所不同吗?和 \n ?

最佳答案

.*本质上是贪婪的,所以它匹配可用的最长匹配:

r'Some text\r(.*)\r
因此给你:
re.findall(r'Some text\r(.*)\r', 'Some text\rText to find !\r other text\r')
['Text to find !\r other text']
但是,如果您更改为非贪婪,则它会给出预期的结果,如下所示:
re.findall(r'Some text\r(.*?)\r', 'Some text\rText to find !\r other text\r')
['Text to find !']

原因 re.findall(r'Some text\n(.*)\n', 'Some text\nText to find !\n other text\n')只给 ['Text to find !']是 DOT 匹配除​​换行符和 \n 之外的任何字符是换行符。如果您启用 DOTALL然后它将再次匹配最长的匹配:
>>> re.findall(r'Some text\n([\s\S]*)\n', 'Some text\nText to find !\n other text\n')
['Text to find !\n other text']

>>> re.findall(r'(?s)Some text\n(.*)\n', 'Some text\nText to find !\n other text\n')
['Text to find !\n other text']
当您使用非贪婪量词时,这再次改变了行为:
re.findall(r'(?s)Some text\n(.*?)\n', 'Some text\nText to find !\n other text\n')
['Text to find !']

关于python - 在python正则表达式中使用\r(回车),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69822726/

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