gpt4 book ai didi

javascript - 在 Python 中用正则表达式替换

转载 作者:太空狗 更新时间:2023-10-30 02:39:10 24 4
gpt4 key购买 nike

考虑 Python 片段:

import re
str = 'that that kitty is cute'

# Anchor at beginning of string
rgexp_start = r'^(.*) \1'
print(re.sub(rgexp_start, r'\1', str))

# Do NOT anchor at beginning of string
rgexp = r'(.*) \1'
print(re.sub(rgexp, r'\1', str))

这打印:

that kitty is cute
thatkittyiscute

为什么第二个正则表达式会删除所有空格?作为一个附加问题,请考虑 JavaScript 片段:

var str = 'that that kitty is cute';
var rgexp_start = /^(.*) \1/;
alert(str.replace(rgexp_start, '$1'));

var rgexp = /(.*) \1/;
alert(str.replace(rgexp, '$1'));

给出两次:

that kitty is cute

为什么 JavaScript 在处理完全相同的正则表达式 方面不同于 Python?

最佳答案

为了回答您的第一个问题,re.sub完全替换为您传递的模式。

因此,r'^(.*)\1' 表示替换所有从头开始 的重复项。既然你指定了从头开始匹配,而字符串只有一个开头,那么唯一能找到匹配替换的就是'^that that',并且这样就完成了。

In[]: 'that that kitty is cute'

'^that that' -> 'that'

Out[]: 'that kitty is cute'

r'(.*)\1' 的情况下,.* 实际上可以匹配 0 个或更多字符。这很重要,因为现在正则表达式不再绑定(bind)到开头。所以它所做的是,除了 '^that that'(第一个正则表达式也这样做)之外,它匹配 '',然后是空格,然后是 '' 一遍,共3次。因此,它将用 '' 替换 ' '(两边带有 ''(空字符串)的空格)。

In[]: 'that that kitty is cute'

'that that' -> 'that'
' ' -> ''
' ' -> ''
' ' -> ''

Out[]: 'thatkittyiscute'

要回答你的第二个问题,b/w python 和 JS 的区别,正如 anubhava 所解释的那样,默认情况下不启用 JS 中的全局标志;仅发生第一个替换,其余字符串保持不变。

关于javascript - 在 Python 中用正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127230/

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