5

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.

2
  • 3
    try escaping the () where you want them as literal tokens. Eg: \(([\s\S]*)\). ( and ) are grouping characters, so you need to explicitly say that they're meant to be literal tokens rather than regex operators. Commented Aug 14, 2017 at 9:41
  • 2
    Did you try regex101.com or any others? it shows you the exect result and also 'explains' your regex-magic spell. you should escape your () characters, so it will tell it from the groups Commented Aug 14, 2017 at 9:48

2 Answers 2

6

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)'
Sign up to request clarification or add additional context in comments.

Comments

4

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)'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.