admin 管理员组

文章数量: 1087829


2023年12月19日发(作者:网页素材星动画)

python 正则匹配词组

Python正则表达式是一种强大的工具,可用于匹配和搜索文本中的特定模式。其中一种应用是匹配词组。

以下是使用 Python 正则表达式匹配词组的示例:

1. 匹配任何包含单词 'apple' 的字符串:

```python

import re

text = 'I like apples and apple pie.'

pattern = r'apple'

matches = l(pattern, text)

print(matches)

```

输出结果为 ['apple', 'apple'],因为字符串中有两个

'apple'。

2. 匹配任何以单词 'python' 开头的字符串:

```python

import re

text = 'Python is a great programming language.'

pattern = r'^Python'

matches = l(pattern, text)

print(matches)

```

- 1 -

输出结果为 ['Python']。

3. 匹配任何以单词 'programming' 结尾的字符串:

```python

import re

text = 'I enjoy programming in Python.'

pattern = r'programming$'

matches = l(pattern, text)

print(matches)

```

输出结果为 ['programming']。

4. 匹配任何包含单词 'apple' 且以单词 'pie' 结尾的字符串:

```python

import re

text = 'I like apple pie, but not apple juice.'

pattern = r'apple.+pie$'

matches = l(pattern, text)

print(matches)

```

输出结果为 ['apple pie']。

以上是一些使用 Python 正则表达式匹配词组的示例。使用正则表达式可以轻松地在文本中搜索和提取特定模式的信息。

- 2 -


本文标签: 匹配 词组 字符串 网页 素材