2

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.

2 Answers 2

1

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

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

5
  • but this adds a comma and space at the last. Commented Jul 10, 2015 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. Commented Jul 10, 2015 at 11:16
  • I added an improved solution. Commented Jul 10, 2015 at 11:24
  • What is [] present at the start.. you may shorten your regex as re.sub(r"\s*\[.*?\]", ", ", s1).rstrip(', ') Commented Jul 10, 2015 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. Commented Jul 10, 2015 at 11:37

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.