如何使用正则表达式仅替换括号内的内容? [英] How to replace only the contents within brackets using regular expressions?
问题描述
如何使用正则表达式只替换括号内的内容?
String = "这是我的字符串 [123]"
我想用 456 替换 123
Desired_String = "这是我的字符串 [456]"
我的尝试:
regex = '.*\[(.*?)\].*'re.sub(正则表达式,'456',字符串)>>456
我不确定要使用什么正则表达式,以便将 123 替换为 456.
如果你稍微修改一下正则表达式和替换字符串,你就会明白:
regex = '\[.*?\]'re.sub(regex,'[456]',String)
您无需将整个字符串与 .*
匹配即可进行替换.
此外,这里并不完全需要,但原始正则表达式字符串是一种很好的做法:
regex = r'\[.*?\]'^
<小时>
另一种选择是使用否定类,这也会更快!
regex = r'[^\[\]]+(?=\])'re.sub(正则表达式,'456',字符串)
可能有点混乱,但是[^\[\]]+
匹配除[
和]
之外的任何字符.>
How to replace only the contents within brackets using regular expressions?
String = "This is my string [123]"
I want to replace 123 with 456
Desired_String = "This is my string [456]"
My attempt:
regex = '.*\[(.*?)\].*'
re.sub(regex,'456',String)
>> 456
I'm not sure what regex to use so that it replaces the 123 with 456.
If you modify your regex and your replacement string a little, you get it:
regex = '\[.*?\]'
re.sub(regex,'[456]',String)
You don't need to match the entire string with .*
for the substitution to work.
Also, it's not entirely required here, but it's good practice to raw your regex strings:
regex = r'\[.*?\]'
^
Another option would be to use negated classes, which will be faster as well!
regex = r'[^\[\]]+(?=\])'
re.sub(regex,'456',String)
It might be a little confusing, but [^\[\]]+
matches any character except [
and ]
.
这篇关于如何使用正则表达式仅替换括号内的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!