在Ubuntu系统中,Python的正则表达式库是re
。要使用正则表达式,首先需要导入re
模块。以下是一些常用的正则表达式操作:
re
模块:import re
pattern = re.compile(r'\d+') # 匹配一个或多个数字
result = pattern.search('There are 123 apples and 456 oranges.')
print(result.group()) # 输出:123
pattern = re.compile(r'\d+')
matches = pattern.findall('There are 123 apples and 456 oranges.')
print(matches) # 输出:['123', '456']
pattern = re.compile(r'\s+') # 匹配一个或多个空白字符
text = 'Hello World! How are you?'
words = pattern.split(text)
print(words) # 输出:['Hello', 'World!', 'How', 'are', 'you?']
pattern = re.compile(r'\d+')
text = 'There are 123 apples and 456 oranges.'
new_text = pattern.sub('NUMBER', text)
print(new_text) # 输出:There are NUMBER apples and NUMBER oranges.
pattern = re.compile(r'^\d+$') # 匹配一个或多个数字,且整个字符串都是数字
text = '123'
match = pattern.match(text)
print(bool(match)) # 输出:True
这些只是re
模块的一些基本功能。正则表达式是一个非常强大的工具,可以用于许多不同的文本处理任务。要了解更多关于Python正则表达式的信息,可以查阅官方文档:https://docs.python.org/3/library/re.html