我试图了解$在python 3.6的re模块中是如何工作的。
python文档说,'$' Matches the end of the string or just before the newline at the end of the string...,我并不完全理解。
你能给我一些re.match中$功能的基本例子吗?
发布于 2017-12-14 02:44:41
$字符始终与输入字符串的末尾匹配。
在多行模式下(例如,当re.M作为标志传递给re函数之一时),它还匹配多行输入的每一行的末尾,就在换行符之前。
你想要一个re.match的例子
some_string = "foo bar baz"
if re.match("foo.*baz$", some_string):
print("Starts with foo and ends with baz") # this will be printed这里的模式中的$字符确保匹配的baz发生在输入字符串的末尾。该模式不会匹配像"foo baz bar"这样的字符串,因为即使发生了baz,它也不在输入的末尾。
使用设置了多行标志的re.match调用通常并不有用。相反,更常见的做法是使用类似于re.findall的方法
multi_line_string = """
foo
bar
foobar
barrel"""
for match in re.findall("^bar$", re.M):
print("bar is whole line") # this will get printed only once给出的模式中的^和$字符确保bar是得到匹配的行的全部内容。没有它们,foobar和barrel也会匹配。
https://stackoverflow.com/questions/47804902
复制相似问题