1

我正在尝试在文本文件中找到以“-”结尾的行。我使用了以下表达式,但没有工作。我不熟悉正则表达式。有人能帮我吗?谢谢你!

if re.match(r'[.*+]+\-+[\r\n]', lines[i]):
    return i
4

3 回答 3

5

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 
于 2013-11-15T03:24:49.667 回答
2

This doesn't really seem like a task that you'd need regex for, but the expression below will do it.

.*-$

Regular expression visualization

.* 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.

于 2013-11-15T03:26:24.947 回答
0

我认为re.search应该更简单

if re.search(r'-$', lines[i]):
    return i
于 2013-11-15T04:19:54.653 回答