python中re库的使用

re 是 Python 内置的正则表达式模块,用于处理字符串匹配和替换。以下是 re 模块的一些常见用法:

  1. 导入 re 模块:
   import re
  1. 匹配字符串:
   pattern = r'hello'
   text = 'hello world'
   match = re.match(pattern, text)
   if match:
       print('Match found:', match.group())
   else:
       print('Match not found')

在上述代码中,re.match() 函数用于匹配以 pattern 开头的字符串。如果匹配成功,则 match.group() 函数将返回匹配的字符串。

  1. 搜索字符串:
   pattern = r'hello'
   text = 'world hello'
   search = re.search(pattern, text)
   if search:
       print('Search found:', search.group())
   else:
       print('Search not found')

在上述代码中,re.search() 函数用于搜索包含 pattern 的字符串。如果找到,则 search.group() 函数将返回匹配的字符串。

  1. 替换字符串:
   pattern = r'world'
   text = 'hello world'
   replace = re.sub(pattern, 'Python', text)
   print('Replaced text:', replace)

在上述代码中,re.sub() 函数用于将 pattern 替换为指定的文本。在上面的例子中,world 被替换为 Python

  1. 分割字符串:
   pattern = r'\s+'
   text = 'hello world'
   split = re.split(pattern, text)
   print('Split text:', split)

在上述代码中,re.split() 函数用于将字符串分割为一个列表,其中分隔符是正则表达式 pattern。在上面的例子中,输入字符串被分割成包含 helloworld 的列表。

这只是 re 模块的一些基本用法,实际上,re 模块还提供了更多功能,如查找所有匹配、使用命名捕获组和预定义字符集等。建议参考 Python 文档以获取更多信息。

发表评论

后才能评论