用正则表达式添加括号

时间:2013-09-22 17:04:08

标签: python regex

您好,

我要将括号加到字母数字组中,中间加上'/',例如:

temp=0E1+3R0/3R3/3R4/2S3/2S4+4HG/4HZ+3RC

应该成为:

temp=0E1+(3R0/3R3/3R4/2S3/2S4)+(4HG/4HZ)+3RC

最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

解决方案

re.sub(r"(\w+/[\w/]+)", r"(\1)", s)

解释

搜索正则表达式:

(       # Put what's inside in group №1
\w+     # Any word character, one or more times
/       # The "/" symbol
[\w/]+  # Any word character or "/" symbol, one or more times
)

替换:

(   # The "(" character, not a group because this is replacing
\1  # The contents of group №1
)   # The ")" character

答案 1 :(得分:0)

没有re

的解决方案
s = 'temp=0E1+3R0/3R3/3R4/2S3/2S4+4HG/4HZ+3RC'

将正确的成员分割为+

right_words = s.split('=')[1].split('+')

在术语

中有操作符号时添加括号
k=0
for w in right_words:
    if '-' in w or '/' in w or '*' in w:
        right_words[k] = '(' + w + ')'
    k+=1

加入

res = s.split('=')[0] + '=' + '+'.join(right_words)

给出

>>> res
'temp=0E1+(3R0/3R3/3R4/2S3/2S4)+(4HG/4HZ)+3RC'