简体   繁体   English

Python 3中的正则表达式替换字符串

[英]Regular expression replace string in Python 3

I am trying to replace a string in Python 3 using regex. 我正在尝试使用正则表达式替换Python 3中的字符串。 I need the string in s1 to be completely replaced with an empty string. 我需要将s1的字符串完全替换为空字符串。

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 输出(实际)- /* 123 */ #没有任何反应

Output (Expected) - BLANK 输出(预期)- BLANK

* 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. 您的代码匹配零个或多个/字符,零个或多个\\s空格,但注释的开头和结尾没有任何文字*字符。

Demo: 演示:

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

\\S+ all no space characters,\\s+ space. \\ S +所有无空格字符,\\ s +空格。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM