在Python中,可以使用*
来表示任意字符通配符。*
可以匹配任意长度的任意字符。下面是使用通配符的一些示例:
- 匹配任意长度的任意字符:
import re pattern = ".*" result = re.match(pattern, "hello") print(result) #
- 匹配以特定字符开头,后面跟任意长度的任意字符:
import re pattern = "he.*" result = re.match(pattern, "hello") print(result) #
- 匹配以任意字符开头,后面跟特定字符:
import re pattern = ".*o" result = re.match(pattern, "hello") print(result) #
- 匹配以特定字符开头和结尾,中间可以是任意字符:
import re pattern = "h.*o" result = re.match(pattern, "hello") print(result) #
需要注意的是,通配符*
是贪婪的,它会尽可能匹配更多的字符。如果需要匹配尽可能少的字符,可以使用.*?
的形式。