欢迎访问宙启技术站
智能推送

Python正则表达式函数:match、search、sub、findall等

发布时间:2023-07-06 17:03:08

正则表达式(regular expression)是一种描述字符串模式的工具,它可以用来进行字符串匹配、查找、替换等操作。Python提供了re模块来支持正则表达式的相关操作。在re模块中,常用的正则表达式函数有match、search、sub和findall等。

1. match函数:从字符串的起始位置开始匹配正则表达式,如果匹配成功则返回一个匹配对象,否则返回None。match函数的语法格式为re.match(pattern, string, flags=0)。

示例代码:

   import re
   result = re.match(r'hello', 'hello world')
   print(result)
   

输出结果为:

   <re.Match object; span=(0, 5), match='hello'>
   

2. search函数:从字符串中搜索正则表达式的匹配项,如果匹配成功则返回一个匹配对象,否则返回None。search函数的语法格式为re.search(pattern, string, flags=0)。

示例代码:

   import re
   result = re.search(r'world', 'hello world')
   print(result)
   

输出结果为:

   <re.Match object; span=(6, 11), match='world'>
   

3. sub函数:替换字符串中的所有匹配项。sub函数的语法格式为re.sub(pattern, repl, string, count=0, flags=0)。其中,pattern是要替换的正则表达式,repl是替换后的字符串,string是要进行替换的原始字符串,count是替换的次数,flags是可选参数。

示例代码:

   import re
   result = re.sub(r'world', 'Python', 'hello world')
   print(result)
   

输出结果为:

   hello Python
   

4. findall函数:查找字符串中所有匹配的子串,并以列表的形式返回。findall函数的语法格式为re.findall(pattern, string, flags=0)。

示例代码:

   import re
   result = re.findall(r'\d+', '2022年是中国的丙寅年')
   print(result)
   

输出结果为:

   ['2022']
   

以上是常用的几个正则表达式函数,在实际应用中可以根据需求选择合适的函数来进行字符串匹配、查找和替换,提高程序的灵活性和效率。