python的re命令
正则表达式是一种强大的文本处理工具。Python中的re模块提供了对正则表达式的支持。re模块提供了许多函数用于对字符串进行正则表达式操作。
其中,最经常使用的就是search和match函数。search函数返回第一个匹配的字符串,而match函数只在字符串开始处匹配。下面是两个函数的用法:
import re # search函数 string = "Python is a good language" match = re.search("good", string) if match: print("match found: ", match.group()) else: print("match not found") # match函数 string = "Python is a good language" match = re.match("good", string) if match: print("match found: ", match.group()) else: print("match not found")
除search和match函数,re模块还提供了其他的一些有用的函数。例如,用sub函数可以将字符串中的某些部份替换成其他内容。下面是一个例子:
import re string = "Python is a good language" new_string = re.sub("good", "great", string) print(new_string)
上面的代码中,使用sub函数将字符串中的"good"替换为"great"。
除函数,re模块还支持一些特殊字符和语法。例如,"."代表任意字符,"^"代表字符串的开始,"$"代表字符串的结尾,"[]"代表一组字符中的任意一个,"|"代表逻辑或。下面是一个示例:
import re string = "Python is a good language" match = re.search("^Python.*good$", string) if match: print("match found: ", match.group()) else: print("match not found") string = "Python is a great language" match = re.search("good|great", string) if match: print("match found: ", match.group()) else: print("match not found")
上面的代码中,"^Python.*good$"表示查找以"Python"开头,以"good"结尾的字符串。而"good|great"则表示查找字符串中既包括"good"又包括"great"的部份。
文章来源:丸子建站
文章标题:python的re命令
https://www.wanzijz.com/view/69843.html