如何运用PYTHON正则表达式的问号?

 时间:2026-02-14 23:27:13

1、打开JUPYTER NOTEBOOK,新建一个空白的文档。

如何运用PYTHON正则表达式的问号?

2、import re

要用正则表达式,那么我们必须引入re模块。

如何运用PYTHON正则表达式的问号?

3、aRegex = re.compile(r'(good)man')

search = aRegex.search('You are the best goodman.')

search.group()

search.group(1)

search.group(2)

如果我们要找到某个数字是否在某个字符串里面,那么有可能会用到分组,而分组里面有很多不同的方法。

如何运用PYTHON正则表达式的问号?

4、bRegex = re.compile(r'(bad)?man')

search1 = bRegex.search('You are the good man.')

search1.group()

如果我们在括号外面加一个问好,就表示这个括号里的可有可无,有就返回。

如何运用PYTHON正则表达式的问号?

5、search2 = bRegex.search('You are the badman.')

search2.group()

这个情况下有出现,所以就返回。

如何运用PYTHON正则表达式的问号?

6、cRegex = re.compile(r'(you )\? I')

search3 = cRegex.search('Who are you ? I am Peter.')

search3.group()

如果刚好我们要找到是问号,那么要用\来跳过,这样就不会出现上诉的方法。

如何运用PYTHON正则表达式的问号?

7、dRegex = re.compile(r'(C)?8\?')

search4 = dRegex.search('The correct number is C8?')

search4.group()

也可以同时出现。

如何运用PYTHON正则表达式的问号?

8、dRegex = re.compile(r'(C)?8?')

search4 = dRegex.search('The correct number is C8?')

search4.group()

这里显示如果没有\的时候,就会出现的状况。

如何运用PYTHON正则表达式的问号?

  • 如何禁止终端服务器管理员远程安装程序
  • 怎么在myeclipse里查看jar包的源代码
  • PPT如何快速替换文本字体
  • 封面如何不设置页码
  • 如何在正文部分开始添加页码
  • 热门搜索
    日内瓦旅游 三亚 旅游 旅游圈 南阳旅游景点大全 贵州旅游局 西藏旅游注意事项 哈密旅游 顺义旅游 常熟旅游网 雪乡旅游攻略