Python 使用正则表达式读取注释行内的内容
我有一根绳子Python 使用正则表达式读取注释行内的内容,python,regex,Python,Regex,我有一根绳子 /* @TS 1 This is the comment for method1 /* @TS 2 This is the comment for method2*/ 我需要将每个索引值(1,2)映射到该内容,如 1->这是method1的注释 我使用常规的 表情 regex = r"/\*([^*]|[\r\n]|(\*([^/]|[\r\n])))*\*/" 是否有任何正则表达式将编号作为一个组,并将(:)之后的内容作为一个组?您可以使用 import re s = "
/* @TS 1 This is the comment
for method1
/* @TS 2 This is the comment
for method2*/
我需要将每个索引值(1,2)映射到该内容,如
1->这是method1的注释
我使用常规的
表情
regex = r"/\*([^*]|[\r\n]|(\*([^/]|[\r\n])))*\*/"
是否有任何正则表达式将编号作为一个组,并将(:)之后的内容作为一个组?您可以使用
import re
s = "/* @TS 1 : This is the comment\n* for method1\n*/\n/* @TS 2 : This is the comment\n* for method2\n*/"
rx = r'/\*+\s*@TS\s*(\d+)\s*:([^*]*\*+(?:[^/*][^*]*\*+)*/)'
d = {}
for match in re.finditer(rx, s):
d[match.group(1)] = re.sub(r"(?:^|[\r\n]+)\s*\*\s*", "", match.group(2)[:-2].strip())
print(d) # => {'1': 'This is the commentfor method1', '2': 'This is the commentfor method2'}
见
这里有几点需要注意
图案细节
-匹配注释开始/\*+
和之后的任何0+/*
*
-0+空格\s*
-文字子字符串@TS
-0+空格\s*
-第1组:一个或多个数字(\d+)
-0+空格和\s*:
:
-(第2组开始):匹配0+个字符,而不是([^*]*\*+
,后跟1+文字*
*
-0+序列:(?:[^/*][^*]*\*+)*
-不是[^/*][^*]*\*+
或/
(与*
匹配),后跟0+非星号字符([^/*]
),后跟1+星号([^*]*
)\*+
-结束/)
(第2组结束)/
空字典是用
d={}
定义的。然后,使用re.finditer
找到所有匹配项,并且match.group(1)
是键,而match.group(2)
包含需要稍微“修剪”的值。最后2个字符用[:-2]
删除(因为它们是*/
),然后从空白中去除值(.strip()
),然后用(?:^ |[\r\n]+)\s*\*\s*
模式我们删除所有*
,在字符串/行的开头加上空格。你的意思是你想获得一个字典,它的键在@TS
之后是数字?是的,我可以把group1作为键,group2作为值放在字典中,而不是直接使用If条件,因此,您还需要删除每个注释行开头的所有*
,对吗?是的,我将使用replacehey删除。谢谢您的帮助。我希望得到相同的结果。您的代码段也正在删除*