【问题标题】:REGEX parsing commands from latex lines - Python来自乳胶行的正则表达式解析命令 - Python
【发布时间】:2014-06-22 08:35:22
【问题描述】:

我正在尝试从加载的每一行(来自 .tex 文件或来自 lilypond 文件的其他命令为 [\clef, \key, \time])解析并删除任何 \command\textit 等...)。

我该怎么做?

我尝试过的

import re
f = open('example.tex')
lines = f.readlines()
f.close()

pattern = '^\\*([a-z]|[0-9])' # this is the wrong regex!!
clean = []
for line in lines:
    remove = re.match(pattern, line)
    if remove:
        clean.append(remove.group())

print(clean)

示例

输入

#!/usr/bin/latex

\item More things
\subitem Anything

预期输出

More things
Anything

【问题讨论】:

    标签: python regex latex lilypond


    【解决方案1】:

    您可以使用this pattern ^\\[^\s]* 使用简单的正则表达式替换:

    python 中的示例代码:

    import re
    p = re.compile(r"^\\[^\s]*", re.MULTILINE)
    
    str = '''
    \item More things
    \subitem Anything
    '''
    
    subst = ""
    
    print re.sub(p, subst, str)
    

    结果是:

    More things
    Anything
    

    【讨论】:

      【解决方案2】:

      这将起作用:

      '\\\w+\s'
      

      它搜索反斜杠,然后搜索一个或多个字符,以及一个空格。

      【讨论】:

      • 您好,感谢您的回答。我也尝试与 '^\\\w+\s' 一起使用,但效果不佳。
      猜你喜欢
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多