Python用一个字替换一个字,然后将下一个字连接起来
我希望能够接收一个字符串,如果r'\snot\s'位于其中,则基本上将“not”与下一个单词连接起来(将两者之间的空格替换为下划线) 所以如果字符串是 string=“不是因为我叫布赖恩,我什么都不高兴” 正则表达式之后的结果将是: “不是因为我叫布赖恩,我什么都不高兴” (没有任何东西是不被触摸的) 我需要找到由空格分隔或在句子开头的“not”,然后将其连接到“u”和下一个单词。使用Python用一个字替换一个字,然后将下一个字连接起来,python,regex,Python,Regex,我希望能够接收一个字符串,如果r'\snot\s'位于其中,则基本上将“not”与下一个单词连接起来(将两者之间的空格替换为下划线) 所以如果字符串是 string=“不是因为我叫布赖恩,我什么都不高兴” 正则表达式之后的结果将是: “不是因为我叫布赖恩,我什么都不高兴” (没有任何东西是不被触摸的) 我需要找到由空格分隔或在句子开头的“not”,然后将其连接到“u”和下一个单词。使用re.sub()保存组: >>> re.sub(r"not\s\b(.*?)\b", r"no
re.sub()
保存组:
>>> re.sub(r"not\s\b(.*?)\b", r"not_\1", string)
'not_that my name is Brian and I am not_happy about nothing'
not\s\b(.*?\b
此处将匹配not
,后跟空格,后跟单词(\b
是单词边界)。(.*)
是一个捕获组,帮助我们捕获非后面的单词,然后我们可以在替换(\1
)中引用该单词。使用re.sub()
和保存组:
>>> re.sub(r"not\s\b(.*?)\b", r"not_\1", string)
'not_that my name is Brian and I am not_happy about nothing'
not\s\b(.*?\b
此处将匹配not
,后跟空格,后跟单词(\b
是单词边界)。(.*)
是一个捕获组,它帮助我们捕获not
后面的单词,然后我们可以在替换(\1
)中引用它。为什么不在字符串上使用replace方法呢?它比正则表达式更具可读性
>>> msg = "not that my name is Brian and I am not happy about nothing"
>>> msg.replace('not ', 'not_')
'not_that my name is Brian and I am not_happy about nothing'
为什么不在字符串上使用replace方法呢?它比正则表达式更具可读性
>>> msg = "not that my name is Brian and I am not happy about nothing"
>>> msg.replace('not ', 'not_')
'not_that my name is Brian and I am not_happy about nothing'
那就:
\bnot\s
示例:
>>> string
'not that my name is Brian and I am not happy about nothing'
>>> re.sub(r'\bnot\s', 'not_', string)
'not_that my name is Brian and I am not_happy about nothing'
那就:
\bnot\s
示例:
>>> string
'not that my name is Brian and I am not happy about nothing'
>>> re.sub(r'\bnot\s', 'not_', string)
'not_that my name is Brian and I am not_happy about nothing'
太好了!你能描述一下正则表达式是如何帮助我理解的吗?(*)我以前没见过。似乎只要找到任何字符,然后再加上一个边界就行了,即re.sub(r“not\s\b(.*\s)\b),r“not\u1”,string),但它只找到字符串中的第一个字符,这很好!你能描述一下正则表达式是如何帮助我理解的吗?(*)我以前没见过。似乎只要找到任何字符,然后再加上一个边界就行了,即re.sub(r“not\s\b(.*\s)\b),r“not\u1”,string),但它只找到字符串中的第一个字符,需要学习很多