0

我想用一些内联注释块解析一个字符串,比如/* comments */,我想忽略这些注释。

例如,

>>> import shlex
>>> string = "foo /bar /* this is a test */"
>>> lex = shlex.shlex(string)
>>> list(lex)
['foo', 'bar', '/', '*', 'this', 'is', 'a', 'test', '*', '/']

如果我添加评论/*者,这将被解释为两个评论者/*并且我错过了/bar

>>> import shlex
>>> string = "foo /bar /* this is a test */"
>>> lex = shlex.shlex(string)
>>> list(lex)
['foo']

理想情况下,我希望结果为

['foo', '/bar']

ps,至于@Chillie 的评论为什么不使用正则表达式。我之所以选择是shlex因为我确实想用它shlex来忽略字符串子引号中的空格。

例如,真实的用例可以是

>>> import shlex
>>> string = "foo /bar \"value string\" /* this is a test */"

我想捕获value string引号中的,但不被引号内的空格分割,

>>> ['foo', '/bar', '\"value string\"']

我不是正则表达式专家。为这种情况设计一个好的模式对我来说有点困难。如果有人能想出一个正则表达式解决方案,我也很好。

4

0 回答 0