杰瑞科技汇

Python正则如何精准匹配空格?

在 Python 中,可以使用正则表达式来匹配空格,以下是几种常见的匹配空格的方法:

Python正则如何精准匹配空格?-图1
(图片来源网络,侵删)

匹配单个空格

使用 \s 可以匹配任何空白字符(包括空格、制表符 \t、换行符 \n 等),如果只想匹配空格(` `),可以使用:

import re
text = "hello world  python"
pattern = r' '  # 直接匹配空格
matches = re.findall(pattern, text)
print(matches)  # 输出: [' ', ' ', ' ']

匹配一个或多个连续空格

使用 匹配一个或多个空格:

pattern = r' +'  # 匹配1个或多个连续空格
matches = re.findall(pattern, text)
print(matches)  # 输出: [' ', '  '](第二个是两个连续空格)

匹配任意空白字符(包括空格、制表符、换行符等)

使用 \s 匹配所有空白字符:

pattern = r'\s'  # 匹配所有空白字符
matches = re.findall(pattern, text)
print(matches)  # 输出: [' ', ' ', ' ', ' '](包括空格和可能的\t、\n等)

匹配开头或结尾的空格

使用 ^\s+ 匹配开头的空格,\s+$ 匹配结尾的空格:

Python正则如何精准匹配空格?-图2
(图片来源网络,侵删)
text = "  hello world  "
pattern_start = r'^\s+'  # 开头空格
pattern_end = r'\s+$'    # 结尾空格
start_matches = re.findall(pattern_start, text)
end_matches = re.findall(pattern_end, text)
print(start_matches)  # 输出: ['  ']
print(end_matches)    # 输出: ['  ']

去除字符串中的所有空格

使用 re.sub() 替换空格:

cleaned_text = re.sub(r' ', '', text)  # 去除所有空格
print(cleaned_text)  # 输出: "helloworldpython"

匹配前后有空格的单词

例如匹配 "word" 前后有空格的情况:

text = "hello world python"
pattern = r'\s\w+\s'  # 匹配前后有空格的单词
matches = re.findall(pattern, text)
print(matches)  # 输出: [' world ', ' python ']

匹配制表符(\t)或换行符(\n

text = "hello\tworld\npython"
pattern = r'\t|\n'  # 匹配\t或\n
matches = re.findall(pattern, text)
print(matches)  # 输出: ['\t', '\n']

需求 正则表达式 说明
匹配单个空格 ` ` 直接匹配空格
匹配1个或多个连续空格 使用 表示重复
匹配所有空白字符 \s 包括空格、\t\n
匹配开头空格 ^\s+ ^ 表示字符串开头
匹配结尾空格 \s+$ 表示字符串结尾
去除所有空格 re.sub(r' ', '', text) 替换空格为空字符串

根据具体需求选择合适的正则表达式即可!

Python正则如何精准匹配空格?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇