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

2025-05-25 23:49:25

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 an蟠校盯昂d 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)')se锾攒揉敫arch = 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|
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢