简体   繁体   English

如何使用正则表达式替换 substring?

[英]How to use regex sub to replace a substring?

My questions is how can I use regex sub in a way that the substituted substring is obtained by mutating the matched part?我的问题是如何使用 regex sub 以通过改变匹配部分获得替换的 substring 的方式? Let me explain if original string is "The most comment log in coding is Hello World" then the modified string should be "The1 most comment log in coding is Hello1 World1"让我解释一下如果原始字符串是“编码中评论最多的日志是Hello World”,那么修改后的字符串应该是“编码中评论最多的1条日志是Hello1 World1”

lets say regex is r'[AZ][az]+'可以说正则表达式是r'[AZ][az]+'

How can I add something after or importantly in-between each match?我如何在每场比赛之后或重要的比赛之间添加一些东西?

Please help me out here请帮帮我

I have tried regex sub, split etc我试过正则表达式子,拆分等

This should do the trick but you would need to provide a string这应该可以解决问题,但您需要提供一个字符串

suffix="1"
x = "The most comment log in coding is Hello World"
for i in re.finditer('[A-Z][a-z]+', x):
    x = x.replace(i.group(), f"{i.group()}{suffix}")
print(x)

output output

The1 most comment log in coding is Hello1 World1

It appears that you only wish to append the value where the word starts with a capital letter, this is an assumption but if so something like this would be fit;看来您只希望 append 单词以大写字母开头的值,这是一个假设,但如果是这样的话,这样的东西是合适的;

import regex as re
startingString = "The most comment log in coding is Hello World"
appendedValue = "1"
pattern = re.compile(r'\b[A-Z]\w*\b')
print(pattern.sub(r'\g<0>'+appendedValue, startingString))

Output: Output:

The1 most comment log in coding is Hello1 World1

You could use \g<0> to refer to the full match, and then append 1 after it.您可以使用\g<0>来引用完整匹配项,然后在其后使用 append 1

import re
s = "The most comment log in coding is Hello World"
print(re.sub(r"[A-Z][a-z]+", r"\g<0>1", s))

Output Output

The1 most comment log in coding is Hello1 World1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM