首页 > 编程知识 正文

Python中的字符串通配符用法介绍

时间:2023-11-22 10:19:39 阅读:306331 作者:YXHC

字符串通配符是在字符串匹配过程中使用的特殊符号,用来表示模糊的匹配规则。Python中提供了一些常用的字符串通配符,可以方便地进行字符串的匹配和替换。

一、通配符*

通配符*表示匹配任意长度的字符串,可以是0个字符也可以是多个字符。

示例代码:

import re

str1 = "hello world"

result = re.findall("he.*ld", str1)
print(result)

输出结果为:['hello world']

这里的.*表示匹配任意长度的任意字符,通过将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hello world'

二、通配符?

通配符?表示匹配任意一个字符。

示例代码:

import re

str1 = "hello world"

result = re.findall("he..o", str1)
print(result)

输出结果为:['hello']

这里的..表示匹配两个任意字符,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hello'

三、通配符[]

通配符[]表示匹配指定字符集合中的任意一个字符。

示例代码:

import re

str1 = "hello world"

result = re.findall("h[eo]llo", str1)
print(result)

输出结果为:['hello']

这里的[eo]表示匹配字符eo,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hello'

四、通配符d

通配符d表示匹配任意一个数字字符。

示例代码:

import re

str1 = "12345"

result = re.findall("dd", str1)
print(result)

输出结果为:['12', '34']

这里的d表示匹配任意一个数字字符,将匹配结果赋值给result变量,我们可以得到匹配到的数字字符'12''34'

五、通配符w

通配符w表示匹配任意一个字母、数字或下划线字符。

示例代码:

import re

str1 = "hello_world"

result = re.findall("www", str1)
print(result)

输出结果为:['hel', 'lo_', 'wor']

这里的w表示匹配任意一个字母、数字或下划线字符,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hel''lo_''wor'

六、通配符.

通配符.表示匹配任意一个字符,但不包括换行符。

示例代码:

import re

str1 = "hellonworld"

result = re.findall("hello.world", str1, re.DOTALL)
print(result)

输出结果为:['hellonworld']

这里的hello.world表示匹配字符串helloworld之间的任意字符,包括换行符,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hellonworld'

七、通配符^和$

通配符^表示匹配字符串的开始位置,$表示匹配字符串的结束位置。

示例代码:

import re

str1 = "hello world"

result = re.findall("^hello", str1)
print(result)

输出结果为:['hello']

这里的^hello表示匹配以字符串hello开头的字符串,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'hello'

示例代码:

import re

str1 = "hello world"

result = re.findall("world$", str1)
print(result)

输出结果为:['world']

这里的world$表示匹配以字符串world结尾的字符串,将匹配结果赋值给result变量,我们可以得到匹配到的字符串'world'

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。