Python 如何使用正则表达式匹配空白字符
正则表达式,通常称为RegEx,是一串与文本字符串中的字母、单词或字符模式相对应的字符。这意味着你可以使用正则表达式来匹配和提取文本中的任何字符串模式。搜索和替换过程受益于正则表达式的使用。最常见的应用是搜索与模式匹配的子字符串,并进行替换。
什么是空白字符
“空白字符”指任何表示水平或垂直空间的字母或字符集。使用正则表达式,元字符 “\s” 可以匹配Python中的空白字符。
步骤
- 导入re函数。
-
初始化一个字符串。
-
使用元字符\s来匹配Python中的空白字符。
-
使用findall方法,将’ \s’元字符和字符串作为参数。
-
打印结果并获取匹配的空白字符。
语法
Result = re.findall(r'[\s]', str)
re.findall():以字符串列表的形式返回字符串中所有非重叠的pattern匹配项。字符串从左到右扫描,匹配项按照找到的顺序返回。
regx = re.compile('\W')
re.compile():我们可以将正则表达式编译为regex对象,以便在不同的目标字符串中查找相同模式的出现,而无需重写它。
Result = regx.findall(str)
re模块提供了一系列方法,让我们可以在字符串中查找匹配:
Findall:返回所有匹配项的列表。
split:返回一个列表,其中包含每次匹配时分割的字符串。
Sub:将字符串替换为一个或多个匹配项。
- search- 如果字符串中有匹配项,则返回一个 Match 对象。
示例1:如何在Python中匹配空格
#importing re function
import re
#initialising a string str
str= 'The Psychology of Money.'
#storing the value of findall method in a variable result
result = re.findall(r'[\s]', str)
#printing the result
print('The give string is \n',str)
print('It has',len(result),'WhiteSpaces')
print (result)
输出
上面代码中的字符串有3个空格。同样,以下是上述命令的输出结果 –
('The give string is \n', 'The Psychology of Money.')
('It has', 3, 'WhiteSpaces')
[' ', ' ', ' ']
代码解释
我们引入re模块来使用正则表达式在Python中匹配空白。下一步是初始化变量“str”,其中包含我们想要匹配空白的字符串。使用元字符“\s”可以在Python中使用正则表达式来检查空白。
一个名为“result”的变量存储了python函数findall()的结果。这个函数在整个文本中搜索模式出现的所有实例。它接受两个参数,元字符“[\s]”和字符串“str”。最后一步是将结果作为输出进行打印。
示例
#importing re function
import re
#initializing a string str
str= "Honesty is the best policy."
#storing the value of findall method in a variable result
result = re.findall(r'[\s]', str)
#printing the result
print('The given string is \n',str)
print('It has',len(result),'WhiteSpaces')
print (result)
输出
上述代码中的字符串有4个空格。同样,以下是上述命令的输出:
('The given string is \n', 'Honesty is the best policy.')
('It has', 4, 'WhiteSpaces')
[' ', ' ', ' ', ' ']
示例
#importing re function
import re
#Taking input from the user and storing it in a string str
str= 'Honesty is the best policy'
#initialising regex, which will compile all matching word characters
regx = re.compile('\W')
#storing the value of findall method in a variable result
result = regx.findall(str)
#printing the result
print('The given string is \n',str)
print('It has',len(result),'WhiteSpaces')
print (result)
输出
上述命令的输出如下:
('The given string is \n', 'Honesty is the best policy')
('It has', 4, 'WhiteSpaces')
[' ', ' ', ' ', ' ']
代码解释
我们加载re模块以在Python中使用正则表达式匹配空格。下一步是要求用户提供一个包含我们希望匹配的空格的字符串输入。在Python中使用正则表达式时,元字符”s”用于匹配空格。
Python的findall方法存储在名为”result”的变量中。该方法在文本中查找模式的每个实例。它需要元字符”[\s]”和字符串”str”作为两个参数。输出返回用户提供的字符串中存在的空格。
结论
正则表达式是一种提供搜索模式的专用文本字符串。它们是表示文本字符串中某些字母、单词或字符组合的一系列字符。re模块用于处理正则表达式。元字符‘\s’用于使用正则表达式在python中匹配空格。
RegEx中最常用的函数是findall()、search()、split()和sub()。锚点、字符集合和修饰符是正则表达式结构的关键组成部分。