如何运用PYTHON正则表达式的pipe|

 时间:2026-02-16 10:29:12

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

如何运用PYTHON正则表达式的pipe|

2、import re

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

如何运用PYTHON正则表达式的pipe|

3、text = "Peter and Ben with Joyce and Alice."

newRegex = re.compile(r'Ben|Alice')

search = newRegex.search(text)

search.group()

我们要找到一句话里面是否有我们要找的其中两个单词之一,返回第一个单词。

如何运用PYTHON正则表达式的pipe|

4、search.group(0)

search.group(1)

注意这里填写1是不返回任何东西的。

如何运用PYTHON正则表达式的pipe|

5、text = "Peter and Ben with Joyce and Alice."

otherRegex = re.compile(r'Chris|Ben')

search = otherRegex.search(text)

search.group()

如果我们要找到第一个单词不存在,那么会默认寻找第二个,不会出错。

如何运用PYTHON正则表达式的pipe|

6、aRegex = re.compile(r'a(pple|rrange|ero|o)')

search = aRegex.search('I\'ve an apple and I will arrange for you.')

search.group()

search.group(1)

search.group(2)

我们还可以设定首个字母相同的单词来寻找。

如何运用PYTHON正则表达式的pipe|

7、bRegex = re.compile(r'c\||aaa')

search = bRegex.search('The sign is c|')

search.group()

如果|本来就是我们要寻找的词,那么就要用\来表示,这样才不会出错。

如何运用PYTHON正则表达式的pipe|

  • 如何运用PYTHON正则表达式字符组
  • 如何运用PYTHON正则表达式的sub()函数
  • 如何运用PYTHON正则表达式的中括号[]
  • 如何运用PYTHON正则表达式的findall()
  • python正则表达式(二)
  • 热门搜索
    发天空照朋友圈配句 怎么去头油 cad三维图怎么画 如何注册商标 怎么去黑痘印 合肥师范学院怎么样 枸杞子怎么吃效果最好 如何学粤语 笔记本没声音怎么回事 192.168.1.1 路由器设置