使用Python /正则表达式优化字符串

时间:2019-03-23 08:58:58

标签: python regex python-3.x regular-language

请帮助我使用python / regex完善此字符串。 它也有很大的空格。

/**
         * this is comment                this is comment
         * this is comment
         * <blank line>
         *      this is comment
         * this is comment
         * <blank line>
         * this is comment
         */

如何通过删除/ **,*

获得纯文本

我希望输出字符串应该是:

这是评论
这是评论
这是评论
这是评论
这是评论

2 个答案:

答案 0 :(得分:2)

现在很明显,OP希望该评论this is comment出现六次,因此,我建议使用此正则表达式,

^[ /*]+\n?| {2,}(.*(\n))

然后将其替换为\2\1

Demo

此外,您确实不需要三个单独的正则表达式(作为其他公认的答案)即可实现,而只需使用一个正则表达式即可。

这是一个Python代码演示,

import re

s = '''/**
         * this is comment                this is comment
         * this is comment
         * 
         *      this is comment
         * this is comment
         * 
         * this is comment
         */'''

print(re.sub(r'(?m)^[ /*]+\n?| {2,}(.*(\n))', r'\2\1', s))

打印后,注意到FailSafe建议我在正则表达式之前使用(?m)启用了多行模式,并非常感谢他的建议,因为它在其他方面并不引人注目,

this is comment
this is comment
this is comment
this is comment
this is comment
this is comment

让我知道您是否需要解释我的答案中的任何部分。

答案 1 :(得分:1)

您可以使用sub()模块中的RegEx函数来匹配不需要的字符并格式化输入字符串。这是一个概念证明,可提供所需的输出。您可以在这里进行测试:https://repl.it/@glhr/regex-fun

import re

inputStr = """/**
         * this is comment                this is comment
         * this is comment
         * 
         *      this is comment
         * this is comment
         * 
         * this is comment
         */"""

formattedStr = re.sub("[*/]", "", inputStr) # comments
formattedStr = re.sub("\n\s{2,}|\s{2,}", "\n", formattedStr) # extra whitespaces
formattedStr = re.sub("^\n+|\n+$|\n{2,}", "", formattedStr) # extra blank lines
print(formattedStr)

您可以在https://regexr.com/等网站上尝试使用正则表达式