San
San

Reputation: 27

Regular expression replace string in Python 3

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

Upvotes: 1

Views: 8505

Answers (2)

Shenglin Chen
Shenglin Chen

Reputation: 4554

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

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121654

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

Upvotes: 6

Related Questions