python 正则 字符串中的日期
时间: 2023-10-19 08:07:48 浏览: 38
如果你想用正则表达式在字符串中匹配日期,可以尝试以下代码:
```python
import re
text = "Today is 2022-02-25, and tomorrow is 2022/02/26."
date_regex = re.compile(r"\d{4}[-/]\d{2}[-/]\d{2}")
matches = date_regex.findall(text)
print(matches) # ['2022-02-25', '2022/02/26']
```
这段代码中,`re.compile()`函数用来编译正则表达式,`\d`表示数字,`{4}`表示匹配4个数字,`[-/]`表示匹配 `-` 或 `/`,`\d{2}`表示匹配2个数字,最后得到的 `matches` 列表中就是所有匹配到的日期字符串。
相关问题
python正则字符串匹配
Python中使用re模块进行正则表达式的字符串匹配。以下是一个简单的例子:
```python
import re
text = "The quick brown fox jumps over the lazy dog"
# 匹配所有小写字母
pattern = r"[a-z]+"
matches = re.findall(pattern, text)
print(matches) # ['he', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
# 匹配所有单词
pattern = r"\b\w+\b"
matches = re.findall(pattern, text)
print(matches) # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
```
在上面的例子中,我们使用`re.findall()`函数来查找文本中所有匹配正则表达式模式的字符串。在第一个例子中,我们使用`[a-z]+`模式匹配所有小写字母字符串,而在第二个例子中,我们使用`\b\w+\b`模式匹配所有单词。
python正则匹配字符串中数字部分
可以使用正则表达式来匹配字符串中的数字部分。例如,匹配字符串中第一个出现的数字可以使用以下代码:
```python
import re
string = "abc123def456"
match = re.search(r'\d+', string)
if match:
print(match.group(0))
```
上述代码中,`re.search()` 函数使用 `\d+` 正则表达式来匹配字符串中的数字部分。`\d` 表示匹配数字,`+` 表示匹配一个或多个数字。如果匹配成功,`match.group(0)` 将返回匹配到的字符串。在本例中,输出结果为 `123`。
如果需要匹配字符串中所有的数字,可以使用 `re.findall()` 函数:
```python
import re
string = "abc123def456"
matches = re.findall(r'\d+', string)
print(matches)
```
上述代码中,`re.findall()` 函数使用 `\d+` 正则表达式来匹配字符串中的数字部分,并返回所有匹配的字符串。在本例中,输出结果为 `['123', '456']`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)