你怎么知道的重新匹配以及检索与“^”不同?

2024-04-25 06:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

看来重新匹配以及检索是一样的,除了检索 可以使用关于多行旗帜使它更加灵活。你知道吗

string ="""U.S. stock-index futures pointed
to a solidly higher open on Monday
North Korea. That issue overshadowed the state of 
the equity market, where earnings 
have been strong at a time of high 
employment and low inflation, 
as well as valuations that a
ppear elevated by many metrics, north korea"""

import re


re.search('^North Korea\.?', string)  # no match
re.match('^North Korea\.?', string) # no match
re.search('^North Korea\.?', string, flags = re.MULTILINE ).group() #match

使用一个比另一个有什么好处吗?你知道吗


Tags: ofthenoresearchstringindexas
1条回答
网友
1楼 · 发布于 2024-04-25 06:44:09

re.match()只在开头检查匹配项

>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match
<_sre.SRE_Match object at ...>

你知道吗检索()检查字符串中的任何位置是否匹配。如果要查找子字符串,请使用re.search()

>>> re.match("c", "abcdef")    # No match
>>> re.search("^c", "abcdef")  # No match
>>> re.search("^a", "abcdef")  # Match
<_sre.SRE_Match object at ...>

两种情况下,搜索和匹配都做相同的事情,因为^

^(插入符号)匹配字符串的开头。因此,它的力量检索从字符串的开头搜索(没有多行)。你知道吗

对于^和多行,re.search()re.match()是不同的,因为:

re.match()仅从字符串开头查找。所以,如果第一行不匹配,那么它就是不匹配。你知道吗

re.search()匹配字符串上的任意位置,因此,它可以匹配第二个、第三个。。。新线。你知道吗

document中,它说

Note however that in MULTILINE mode match() only matches at the beginning of the string, whereas using search() with a regular expression beginning with '^' will match at the beginning of each line.

相关问题 更多 >