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

Comments

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 Comments

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

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.