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

使用Python中的re模块进行正则表达式匹配和搜索

发布时间:2024-01-09 06:35:21

re模块是Python中内置的正则表达式模块,用于匹配和搜索文本。下面是一些re模块常用的函数和使用例子。

1. re.match(pattern, string, flags=0)

函数用于尝试从字符串的起始位置匹配一个模式。如果匹配成功,则返回一个匹配对象;否则返回None。

   import re
   
   pattern = r"hello"
   string = "hello world"
   match_obj = re.match(pattern, string)
   
   if match_obj:
       print("Pattern matched.")
   else:
       print("Pattern not matched.")
   

输出结果为:"Pattern matched."

2. re.search(pattern, string, flags=0)

函数用于在字符串中搜索匹配的模式。如果匹配成功,则返回一个匹配对象;否则返回None。

   import re
   
   pattern = r"world"
   string = "hello world"
   search_obj = re.search(pattern, string)
   
   if search_obj:
       print("Pattern found.")
   else:
       print("Pattern not found.")
   

输出结果为:"Pattern found."

3. re.findall(pattern, string, flags=0)

函数用于查找字符串中所有匹配的模式,并以列表的形式返回。

   import re
   
   pattern = r"\d+"
   string = "There are 10 apples and 5 oranges."
   result = re.findall(pattern, string)
   
   print(result)
   

输出结果为:['10', '5']

4. re.sub(pattern, repl, string, count=0, flags=0)

函数用于替换字符串中的匹配项,并返回替换后的字符串。

   import re
   
   pattern = r"apple"
   string = "I have an apple."
   replaced_string = re.sub(pattern, "banana", string)
   
   print(replaced_string)
   

输出结果为:"I have a banana."

5. re.split(pattern, string, maxsplit=0, flags=0)

函数用于通过指定的模式对字符串进行拆分,并返回拆分后的列表。

   import re
   
   pattern = r"\s"
   string = "hello world"
   result = re.split(pattern, string)
   
   print(result)
   

输出结果为:['hello', 'world']

6. 使用正则表达式进行匹配

   import re
   
   pattern = r"(\d{3})-(\d{4})"
   string = "My phone number is 123-4567."
   match_obj = re.match(pattern, string)
   
   if match_obj:
       area_code = match_obj.group(1)
       phone_number = match_obj.group(2)
       print("Area code:", area_code)
       print("Phone number:", phone_number)
   else:
       print("Pattern not matched.")
   

输出结果为:

   Area code: 123
   Phone number: 4567
   

正则表达式是一个强大的工具,用于在文本中查找和操作具有特定模式的字符串。使用re模块可以方便地进行正则表达式的匹配和搜索,而不需要手动处理字符串。