Python使用re模块中的match匹配提取字符串

版权声明:学习分享,共同进步 https://blog.csdn.net/Andrew_jdw/article/details/82801224

在正则表达式中

  1. 点号(.)可以匹配任意字符
  2. 星号(*)可以匹配任意个字符(包括0个)
  3. 加号(+)匹配至少一个字符
  4. 问号(?)匹配零或一个字符
  5. {n}匹配n个字符
  6. {n,m}匹配n-m个字符
  7. 美元符号($)结束符

[]   可以做精准地匹配,表示范围。

比如:

[0-9a-zA-Z] 可以匹配一个数字或字母

[0-9a-zA-Z]+可以匹配至少一个数字或字母组成的字符串

()  表示的是要提取的分组(group)。

比如:

m = re.match(r'^(\d{3})-(\d{3,10})$', '025-7654321')

得到的结果group(0)始终都是字符串本身。 

m.group(0)
Out[103]: '025-7654321'

group(1)是提取的第一个字符串

m.group(1)
Out[104]: '025'

 group(2)是提取的第二个字符串

m.group(2)
Out[105]: '7654321'

 groups()会全部输出一个tuple。

type(m.groups())
Out[107]: tuple
m.groups()
Out[106]: ('025', '7654321')

猜你喜欢

转载自blog.csdn.net/Andrew_jdw/article/details/82801224
今日推荐