请列举Python常用字符正则表达式 ?
参考答案:
在Python中,re
模块提供了正则表达式相关的功能。下面是一些常用的字符正则表达式的例子:
- 匹配任何单个字符:
.
import re
pattern = re.compile('.')
match = pattern.search('hello')
print(match.group()) # 输出 'h'
- 匹配字符串的开始:
^
pattern = re.compile('^hello')
match = pattern.search('hello world')
if match:
print('Matched')
else:
print('Not matched') # 输出 'Not matched'
- 匹配字符串的结束:
$
pattern = re.compile('world$')
match = pattern.search('hello world')
if match:
print('Matched')
else:
print('Not matched') # 输出 'Matched'
- 匹配一个或多个字符:
*
pattern = re.compile('he*lo')
match = pattern.search('hello')
print(match.group()) # 输出 'hello'
match = pattern.search('lo')
print(match.group()) # 输出 'lo'
- 匹配一个或多个前面的元素:
+
pattern = re.compile('he+lo')
match = pattern.search('hello')
print(match.group()) # 输出 'hello'
# 注意:下面的代码不会匹配到任何内容,因为'he'后面没有'lo'
match = pattern.search('he lo')
if match:
print(match.group())
else:
print('Not matched') # 输出 'Not matched'
- 匹配前面的元素零次或一次:
?
pattern = re.compile('colou?r')
match = pattern.search('color')
print(match.group()) # 输出 'color'
match = pattern.search('colour')
print(match.group()) # 输出 'colour'
- 匹配前面的元素n次:
{n}
pattern = re.compile('1{3}')
match = pattern.search('111')
print(match.group()) # 输出 '111'
- 匹配前面的元素n次以上:
{n,}
pattern = re.compile('1{3,}')
match = pattern.search('1111')
print(match.group()) # 输出 '1111'
- 匹配前面的元素n到m次:
{n,m}
pattern = re.compile('1{2,4}')
match = pattern.search('1111')
print(match.group()) # 输出 '1111'
match = pattern.search('11')
print(match.group()) # 输出 '11'
- 匹配数字:
\d
pattern = re.compile('\d+')
match = pattern.search('hello123world')
print(match.group()) # 输出 '123'
- 匹配非数字:
\D
pattern = re.compile('\D+')
match = pattern.search('hello123world')
print(match.group()) # 输出 'hello'
- 匹配空白字符:
\s
pattern = re.compile('\s+')
match = pattern.search('hello world')
print(match.group()) # 输出 ' '
- 匹配非空白字符:
\S
pattern = re.compile('\S+')
match = pattern.search('hello world')
print(match.group()) # 输出 'hello'
- 匹配单词字符:
\w
pattern = re.compile('\w+')
match = pattern.search('hello_world123')
print(match.group()) # 输出 'hello'
- 匹配非单词字符:
\W
pattern = re.compile('\W+')
match = pattern.search('hello_world123')
print(match.group()) # 输出 '_'
这些只是一些基本的例子,实际上正则表达式的功能