python中的正则表达式,%

Mat*_*ech 0 python regex

我是普通表达式的新手,但我找不到关于%char 的特殊规则.

我做以下事情:

line = parseFileHandle.readline()
while 1:
    line = parseFileHandle.readline()
    if not line:
        break
    # test for string '%%?'
    match = re.match("%%?", line)
    if match:
        print (line)
Run Code Online (Sandbox Code Playgroud)

但是会打印出以%char 开头的任何行.那不是我想要的.

最后,我想找出此表单中文件中的文件名(myfile.tex)

%%?  file: myfile.tex
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

问题不在于%.它?具有特殊含义:它使第二个%可选.因此,你的正则表达式将匹配%%%.

以下正则表达式应该起作用:

match = re.match("%%[?]", line)
Run Code Online (Sandbox Code Playgroud)

如果您%%?在行的开头搜索,则不需要正则表达式.以下将实现相同的目标:

if line.startswith("%%?"):
Run Code Online (Sandbox Code Playgroud)