1

I am trying to replace a string in Python 3 using regex. I need the string in s1 to be completely replaced with an empty string.

s1 = "/*  123  */"  # Pattern /*  n  */ where n can be any integer  
s2 = re.sub(r'/*\s*\d+\s*/',"",s1)
print(s2)

Output(Actual) - /* 123 */ # nothing happens

Output (Expected) - BLANK

2 Answers 2

6

* is a meta character, you need to escape it if you want to match a literal * character. You are also missing the literal * character just before the closing /:

s2 = re.sub(r'/\*\s*\d+\s*\*/', "", s1)

Your code was matching zero or more / characters, and zero or more \s spaces, but not any of the literal * characters at the start and end of the comment.

Demo:

>>> import re
>>> s1 = "/*  123  */"
>>> re.sub(r'/\*\s*\d+\s*\*/', "", s1)
''
Sign up to request clarification or add additional context in comments.

Comments

0

\S+ all no space characters,\s+ space.

[31]: re.sub(r'\S+|\s+', "", s1)
Out[31]: ''

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.