我正在尝试在文本文件中找到以“-”结尾的行。我使用了以下表达式,但没有工作。我不熟悉正则表达式。有人能帮我吗?谢谢你!
if re.match(r'[.*+]+\-+[\r\n]', lines[i]):
return i
re.match
仅当它从字符串的开头找到匹配项时才会匹配该字符串。如果真的要使用re.match
,可以使用下面的正则表达式
if re.match(r'.*-$', lines[i].rstrip("\n")):
return i
但是这个任务你根本不需要正则表达式,你可以做这样的事情
for i, line in enumerate(lines):
if line.rstrip("\n")[-1] == "-":
return i
This doesn't really seem like a task that you'd need regex for, but the expression below will do it.
.*-$
.*
will match any character "zero or more" times with $
specifying that -
must be immediately followed by the end of the string.
EDIT
If you set the flag to set ^
and $
to match newlines, it will do just that. I wouldn't recommend matching newline characters explicitly ('\r\n' in your case) as these are dependant on your environment.
By defualt, .*
will not match newlines.
我认为re.search应该更简单
if re.search(r'-$', lines[i]):
return i