在字符串中重新查找日期

re find date in string

谁能解释一下如何使用 re.find all 将日期与以下字符串分开?当日期可以是 1.1.2001 或 11.11.2001 格式之一时。代表天数和月份的字符串中的数字位数不稳定-

import re 
str = "This is my date: 1.1.2001 fooo bla bla bla"
str2 = "This is my date: 11.11.2001 bla bla foo bla"

我知道我应该使用 re.findall(pattern, string) 但老实说我对这些模式完全困惑。我不知道如何 assemble 模式来适应我的情况。

我找到了类似的东西,但我完全不知道为什么模式前有 r 字母... \ 表示字符串开头? d 表示数字? {} 中的数字表示多少?

match = re.search(r'\d{2}.\d{2}.\d{4}', text)

非常感谢!

所以这里发生了两件事

1) 当你输入一些文本 "..." 它首先需要被 python 解释器解释
2) 然后 python 解释器将结果 result("...") 传递给它自己的内部正则表达式解释器

为了匹配像数字这样的特殊字符,python 的内部正则表达式解释器支持像 \d 这样的特殊字符。所以正则表达式解释器期望得到 \d。不幸的是,字符 \ 也是 python 解释器的转义字符。

为了避免 python 解释器吃掉 \ 并且只将 d 传递给正则表达式解释器。我们将 r"..." 放在我们的字符串前面以指示 "raw string" - 这意味着 "Hey python interpreter, don't touch my \ characters!"

使用 r 是一个 raw string 这意味着它不会被字符串

中的 \ 转义或更改

Python 将 \ 描述为:

Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence;

基本上意味着如果您使用一个通常是特殊字符的字符来进行正则表达式,它会忽略它。

{} 用于重复:

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.

意味着它将重复您在 {}

中指定的数字的前一个字符

\d是一个特殊字符,匹配从0到9的任意数字。

强烈推荐你this tutorial

re.findall() returns 使用该正则表达式匹配的所有内容的列表。

字符串的 r 前缀告诉 Python 解释器它是一个 raw string,这实际上意味着反斜杠 \ 不再被视为转义字符,而是文字反斜杠。对于 re 模块,它很有用,因为经常使用反斜杠,所以为了避免大量 \(转义反斜杠),大多数人会使用原始字符串。

你要找的是这个:

match = re.search(r'\d{1,2}\.\d{1,2}\.\d{4}', text)

{} 告诉正则表达式你想要前面的集合出现多少次。 {1,2} 表示最小值 1 和最大值 2 \d{4} 表示完全匹配 4 次。

请注意 . 也被 \. 转义,因为在正则表达式中 . 表示 任何字符 ,但在这种情况下你正在寻找文字 . 所以你转义它告诉正则表达式寻找文字字符。

更多解释见此:https://regex101.com/r/v2QScR/1