简体   繁体   English

如何使用正则表达式替换一些括号而不是其他括号

[英]How to use regex to replace some parentheses but not others

As the title says, I am trying to replace parentheses with brackets conditionally.正如标题所说,我试图有条件地用括号替换括号。 For example, I will have a string like:例如,我将有一个字符串,如:

"(This is some text) but I also have (1) character and not (22) character." “(这是一些文字)但我也有(1)个字符而不是(22)个字符。” The character may be 1 but it could be any singe character.字符可以是 1,但也可以是任何单个字符。

I only want to replace the text that has one character in it.我只想替换其中包含一个字符的文本。 So the above example will be:所以上面的例子将是:

"(This is some text) but I also have [ 1 ] character and not (22) character." “(这是一些文本)但我也有[ 1 ]字符而不是 (22) 字符。”

I have tried using this regex which almost works but I can't get text to remain inside:我试过使用这个几乎可以工作的正则表达式,但我不能让文本留在里面:

re.sub("\(.\)", "\[.\]", a)

Edit: Added clarity that it could be any single character within the parentheseses编辑:增加了清晰度,它可以是括号内的任何单个字符

Use a capture group:使用捕获组:

inp = "(This is some text) but I also have (1) character and not (22) character."
output = re.sub(r'\((.)\)', r'[\1]', inp)
print(output)

This prints:这打印:

(This is some text) but I also have [1] character and not (22) character.

See this :看到这个

>>> x = '(This is some text) but I also have (1) character and not (22) character.'
>>> re.sub('\((.)\)', '[\g<1>]', x)
'(This is some text) but I also have [1] character and not (22) character.'

You need to capture this one character and then use the capture group number to retrieve it.您需要捕获这一个字符,然后使用捕获组号来检索它。

use {} to control how many characters is your target.使用{}控制您的目标字符数。

re.sub(r"\((.{1})\)", r"[\1]", a)

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

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