python:re.Match(r&quot“ 1” [1]&quot返回空的

发布于 2025-01-30 06:22:57 字数 236 浏览 1 评论 0 原文

为什么Python的Regex模块在以下代码中不识别“ [1]”?

In [43]: re.match (r"1",  "[1]")

In [44]:

而这有效:

In [46]: re.match (r"1",  "123")
Out[46]: <re.Match object; span=(0, 1), match='1'>

Why does Python's regex module not recognize "[1]" in this following code?

In [43]: re.match (r"1",  "[1]")

In [44]:

whereas this works:

In [46]: re.match (r"1",  "123")
Out[46]: <re.Match object; span=(0, 1), match='1'>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明月松间行 2025-02-06 06:22:57

来自 docs.pys.python.org

如果在字符串匹配开始时零或更多字符 正则表达式模式,请返回相应的匹配对象。如果字符串与模式不匹配,则不返回;请注意,这与零长度匹配不同。

...

如果要在字符串中找到匹配中的任何地方/3/library/re.html#search-vs-match“ rel =” nofollow noreferrer“> search() vs. vs. match> match() )。

由于您的“字符串”以开头[,因此未捕获。

正如文档所建议的那样,使用 re.search(r“ 1”,“ [1]”)确实与之匹配,因为它可以匹配字符串中的任何位置


这有效:

 在[46]中:re.match(r“ 1”,“ 123”)``
out [46]:&lt; re.Match对象;跨度=(0,1),匹配='1'&gt;
 

这里的“字符串” 开始,并按预期匹配

From docs.python.org:

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

...

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Since your 'string' starts with an [, it's not captured.

As suggested by the docs, using re.search(r"1", "[1]") does match it since it will match anywhere in the string


whereas this works:

In [46]: re.match (r"1",  "123")`
Out[46]: <re.Match object; span=(0, 1), match='1'>

Here the 'string' starts with the pattern and is being matched as expected

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文