Akhil Mathew
Akhil Mathew

Reputation: 1659

Replace text between parentheses in python

My string will contain () in it. What I need to do is to change the text between the brackets.

Example string: "B.TECH(CS,IT)". In my string I need to change the content present inside the brackets to something like this.. B.TECH(ECE,EEE)

What I tried to resolve this problem is as follows..

reg = r'(()([\s\S]*?)())'
a = 'B.TECH(CS,IT)'
re.sub(reg,"(ECE,EEE)",a)

But I got output like this..

'(ECE,EEE)B(ECE,EEE).(ECE,EEE)T(ECE,EEE)E(ECE,EEE)C(ECE,EEE)H(ECE,EEE)((ECE,EEE)C(ECE,EEE)S(ECE,EEE),(ECE,EEE)I(ECE,EEE)T(ECE,EEE))(ECE,EEE)'

Valid output should be like this..

B.TECH(CS,IT)

Where I am missing and how to correctly replace the text.

Upvotes: 4

Views: 8785

Answers (2)

rubenwardy
rubenwardy

Reputation: 683

The problem is that you're using parentheses, which have another meaning in RegEx. They're used as grouping characters, to catch output.

You need to escape the () where you want them as literal tokens. You can escape characters using the backslash character: \(.

Here is an example:

reg = r'\([\s\S]*\)'
a = 'B.TECH(CS,IT)'
re.sub(reg, '(ECE,EEE)', a)
# == 'B.TECH(ECE,EEE)'

Upvotes: 6

cs95
cs95

Reputation: 402363

The reason your regex does not work is because you are trying to match parentheses, which are considered meta characters in regex. () actually captures a null string, and will attempt to replace it. That's why you get the output that you see.

To fix this, you'll need to escape those parens – something along the lines of

\(...\)

For your particular use case, might I suggest a simpler pattern?

In [268]: re.sub(r'\(.*?\)', '(ECE,EEE)', 'B.TECH(CS,IT)')
Out[268]: 'B.TECH(ECE,EEE)'

Upvotes: 4

Related Questions