正则表达式(Python)
正则表达式
元字符
符号 | 含义 |
---|---|
. | 匹配除换行符以外的任意字符 |
\w | 匹配字母、数字、下划线、汉字 |
\s | 匹配任意空白符 |
\d | 匹配数字 |
\b | 匹配单词的开始或结束 |
^ | 匹配字符串的开始 |
$ | 匹配字符串的结束 |
[^abcd] | 匹配出了abcd以外的任意字符 |
字母大写为反义字符
import re #导入re包
string="hellopython20190401@!!hellojava_ helloC语言..."
reg="\d"
result=re.findall(reg,string)
print(result)
[‘2’, ‘0’, ‘1’, ‘9’, ‘0’, ‘4’, ‘0’, ‘1’]
限定符与 贪婪 模式
符号 | 含义 |
---|---|
* | 重复0次或多次 |
+ | 重复一次或多次 |
? | 重复零次或一次 |
{n} | 重复n次 |
{n,} | 重复n次或n次以上 |
{n,m} | 重复n到m次 |
python中默认为贪婪,使用?变为非贪婪
import re
string="hellopython20190401@!! hellojava_ helloC语言..."
reg="\d{4}"
result=re.findall(reg,string)
print(result)
[‘2019’, ‘0401’]
import re
string="hellopython20190401@!! hellojava_ helloC语言..."
reg="[0-9a-z]{4}" #匹配4个数字或小写字母
result=re.findall(reg,string)
print(result)
[‘hell’, ‘opyt’, ‘hon2’, ‘0190’, ‘hell’, ‘ojav’, ‘hell’]
import re
string="my ip 192.168.1.78 | 192.168.1.79"
reg="(\d{1,3}.){3}\d{1,3}"
result=re.search(reg,string)[0] #search只匹配第一个
print(result)
192.168.1.78
组匹配
result.group(n)
re.I忽略大小写
常见的正则表达式
表达式 | 匹配内容 |
---|---|
"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$" | 手机号码 |