Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I've got a string that looks like this:

1080p [2.1GB] 720p [1.3GB] 480p [500MB]

In Python, I want to replace all the [x] with ,. I've tried this code:

import re
s1 = '1080p [2.1GB] 720p [1.3GB] 480p [500MB]'
s2 = re.sub("[(.*?)]", ", ", s1)

However, I get as this output: 1080p [2, 1GB] 720p [1, 3GB] 480p [500MB].

Instead, I would like to obtain something like 1080p, 720p, 480p.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You may use re.split.

>>> s1 = '1080p [2.1GB] 720p [1.3GB] 480p [500MB]'
>>> ', '.join(i for i in re.split(r'\s*\[[^\]]*\]\s*', s1) if i)
'1080p, 720p, 480p'
share|improve this answer

You need to escape the brackets and use raw string:

s2 = re.sub(r"\[(.*?)\]", ", ", s1)

Note that outside of character class, these symbols - .^$*+?()[{\| - should be escaped to match literally.

Here is a demo

If you do not plan to use the contents inside [...], remove the round brackets.

s2 = re.sub(r"\[.*?\]", ", ", s1)

To obtain a "cleaner" string, you may use a bit more sophisticated regex and strip():

import re
s1 = '1080p [2.1GB] 720p [1.3GB] 480p [500MB]'
s2 = re.sub(r"\s*\[.*?\]", ",", s1)
print s2.strip(' ,')

Output of another demo: 1080p, 720p, 480p

share|improve this answer
    
but this adds a comma and space at the last. – Avinash Raj Jul 10 at 11:14
    
@AvinashRaj: I see, but i would like something like 1080p, 720p, 480p just means something similar, so it does answer the main issue why the regex was not working. – stribizhev Jul 10 at 11:16
    
I added an improved solution. – stribizhev Jul 10 at 11:24
    
What is [] present at the start.. you may shorten your regex as re.sub(r"\s*\[.*?\]", ", ", s1).rstrip(', ') – Avinash Raj Jul 10 at 11:32
    
I think I already have it, just did not fix in the demo. I also fixed a typo in the answer just now. I also assume there are always spaces between []s and other entities, otherwise, the replacement string should be as in the original. – stribizhev Jul 10 at 11:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.