gpt4 book ai didi

用于长字符串中注释的 Python 正则表达式

转载 作者:行者123 更新时间:2023-11-28 16:36:59 25 4
gpt4 key购买 nike

我正在尝试为位于长字符串中的 python 注释制定一个好的正则表达式。到目前为止我已经

正则表达式:

#(.?|\n)*

字符串:

'### this is a comment\na = \'a string\'.toupper()\nprint a\n\na_var_name = " ${an.injection} "\nanother_var = " ${bn.injection} "\ndtabse_conn = " ${cn.injection} "\n\ndef do_something()\n    # this call outputs an xml stream of the current parameter dictionary.\n    paramtertools.print_header(params)\n\nfor i in xrange(256):    # wow another comment\n    print i**2\n\n'

我觉得有更好的方法可以从字符串中获取所有单独的评论,但我不是正则表达式方面的专家。有没有人有更好的解决方案?

最佳答案

从索引为 1 的匹配组中获取评论。

(#+[^\\\n]*)

DEMO

示例代码:

import re
p = re.compile(ur'(#+[^\\\n]*)')
test_str = u"..."

re.findall(p, test_str)

匹配:

1.  ### this is a comment
2. # this call outputs an xml stream of the current parameter dictionary.
3. # wow another comment

关于用于长字符串中注释的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24829843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com