【问题标题】:Refine String using Python/Regular Expression使用 Python/正则表达式优化字符串
【发布时间】:2019-08-14 04:19:58
【问题描述】:

请帮助我使用 python/regex 优化此字符串。 它也有很大的空白。

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

如何通过删除 /**, * 得到纯文本

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

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

【问题讨论】:

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


    【解决方案1】:

    现在很明显,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
    

    如果您需要解释我的答案中的任何部分,请告诉我。

    【讨论】:

    • @FailSafe:是的,同意。实际上OP的帖子有点不正确。在他的帖子中,他的预期输出列出了this is comment 五倍,而他实际上预期的六倍,正如预期答案中所见,这就是为什么我认为他不接受我的回答,但这不是我的错:)。另外,当我发布此答案时,我有点着急,否则我也总是提供演示代码解决方案。另一个答案使用三个不同的替换,否则可以使用此正则表达式在单个替换中完成。 Check Demo
    • @"Pushpesh Kumar Rajwanshi" 是的。我看到了这个错误,想知道他是否想把它打破,但这可以忽略不计。尽管如此,我还是在为你 +1,但只是想请你编辑它,因为它提到需要启用多行。
    • @FailSafe:感谢您的支持 :) 感谢您抽出时间阅读我的回答。我已经用一个正则表达式更新了我的答案,它给出了六次列出评论的正确输出,还给出了 python 代码解决方案,也启用了多行模式,并按照你的建议特别提到它,你确实是对的。人们通常倾向于错过这些小属性。
    • @"Pushpesh Kumar Rajwanshi" 废话。 Re.Sub 即时替补!!我花了大约半个小时试图弄清楚你是如何让\ * this is comment this is comment 打印在不同的行上的。哇。我学到了一些新东西。
    • @FailSafe:是的,我的解决方案很好地利用了这一点来获得预期的结果,因此有点不重要。
    【解决方案2】:

    您可以使用RegEx 模块中的sub() 函数来匹配不需要的字符并格式化输入字符串。这是一个概念证明,它给出了你想要的输出。你可以在这里测试: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/ 等网站上试验正则表达式

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2021-03-06
      • 2013-04-26
      • 1970-01-01
      相关资源
      最近更新 更多