23

使用Python正则表达式操作文本数据

 4 years ago
source link: https://segmentfault.com/a/1190000019166942?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

qE3ma2V.jpg!web

  • 来源 | 愿码(ChainDesk.CN) 内容编辑
  • 愿码Slogan | 连接每个程序员的故事
  • 网站 | http://chaindesk.cn
  • 愿码愿景 | 打造全学科IT系统免费课程,助力小白用户、初级工程师0成本免费系统学习、低成本进阶,帮助BAT一线资深工程师成长并利用自身优势创造睡后收入。
  • 官方公众号 | 愿码 | 愿码服务号 | 区块链部落
  • 免费加入愿码全思维工程师社群 | 任一公众号回复“愿码”两个字获取入群二维码

本文阅读时长:7min

什么是正则表达式

正则表达式,是简单地字符的序列,可指定特定的搜索模式。正则表达式已存在很长一段时间,并且它本身就是计算机科学的一个领域。

在 Python中,使用Python的内置re模块处理正则表达式操作 。在本节中,我将介绍创建正则表达式并使用它们的基础知识。您可以使用以下步骤实现正则表达式:

  1. 指定 模式字符串
  2. 将模式字符串编译为正则表达式对象。
  3. 使用正则表达式对象在字符串中搜索模式。
  4. 可选:从字符串中提取匹配的模式。

编写和使用正则表达式

在Python中创建正则表达式的第一步是导入re 模块:

import re

Python正则表达式使用模式字符串表示,模式字符串是指定所需搜索模式的字符串。在最简单的形式中,模式字符串只能由字母,数字和空格组成。以下模式字符串表示精确字符序列的搜索查询。您可以将每个角色视为一个单独的模式。在后面的例子中,我将讨论更复杂的模式:

import re

pattern_string = "this is the pattern"

下一步是将模式字符串处理为Python可以使用的对象,以便搜索模式。这是使用re模块的compile()方法完成的。的编译()方法将图案字符串作为参数并返回一个正则表达式对象:

import re

pattern_string = "this is the pattern" regex = re.compile(pattern_string)

获得正则表达式对象后,可以使用它在 搜索字符串搜索 模式字符串中指定的模式。搜索字符串只是您要在其中查找模式的字符串的名称。要搜索模式,可以使用regex对象的search()方法,如下所示:

import re

pattern_string = "this is the pattern" regex = re.compile(pattern_string)

match = regex.search("this is the pattern")

如果模式字符串中指定的模式位于搜索字符串中,则search()方法将返回匹配对象。否则,它返回None数据类型,这是一个空值。

由于Python相当松散地解释了True和False值,因此搜索函数的结果可以像if语句中的布尔值一样使用,这可能相当方便:

....

match = regex.search("this is the pattern") if match:

print("this was a match!")

这个模式应该产生一个匹配,因为它与模式字符串中指定的模式完全匹配。如果在搜索字符串的任意位置找到模式,搜索函数将生成匹配,如下所示:

....

match = regex.search("this is the pattern") if match:

print("this was a match!")

if regex.search("*** this is the pattern ***"): print("this was not a match!")

if not regex.search("this is not the pattern"): print("this was not a match!")

特殊字符

正则表达式取决于使用某些 特殊字符 来表达模式。因此,除非用于预期目的,否则不应直接使用以下字符:

. ^ $ * + ? {} () [] |

如果确实需要使用模式字符串中的任何前面提到的字符来搜索该字符,则可以编写以反斜杠字符开头的字符。这称为 转义 字符。这是一个例子:

pattern string = "c*b"

## matches "c*b"

如果需要搜索反斜杠字符本身,则使用两个反斜杠字符,如下所示:

pattern string = "cb"

## matches "cb"

匹配空格

在模式字符串中的任何位置使用s都匹配空白字符。这比空格字符更通用,因为它适用于制表符和换行符:

....

a_space_b = re.compile("asb") if a_space_b.search("a b"):

print("'a b' is a match!")

if a_space_b.search("1234 a b 1234"): print("'1234 a b 1234' is a match")

if a_space_b.search("ab"):

print("'1234 a b 1234' is a match")

匹配字符串的开头

如果在模式字符串的开头使用^字符,则只有在搜索字符串的开头找到模式时,正则表达式才会产生匹配:

....

a_at_start = re.compile("^a") if a_at_start.search("a"):

print("'a' is a match")

if a_at_start.search("a 1234"): print("'a 1234' is a match")

if a_at_start.search("1234 a"): print("'1234 a' is a match")

匹配字符串的结尾

类似地,如果在模式字符串的末尾使用$符号,则正则表达式将仅在模式出现在搜索字符串的末尾时生成匹配:

....

a_at_end = re.compile("a$") if a_at_end.search("a"):

print("'a' is a match") if a_at_end.search("a 1234"):

print("'a 1234' is a match") if a_at_end.search("1234 a"):

print("'1234 a' is a match")

匹配一系列字符

可以匹配一系列字符而不是一个字符。这可以为模式增加一些灵活性:

[A-Z] matches all capital letters

[a-z] matches all lowercase letters

[0-9] matches all digits

....

lower_case_letter = re.compile("[a-z]") if lower_case_letter.search("a"):

print("'a' is a match")

if lower_case_letter.search("B"): print("'B' is a match")

if lower_case_letter.search("123 A B 2"): print("'123 A B 2' is a match")

digit = re.compile("[0-9]") if digit.search("1"):

print("'a' is a match") if digit.search("342"):

print("'a' is a match") if digit.search("asdf abcd"):

print("'a' is a match")

匹配几种模式中的任何一种

如果存在构成匹配的固定数量的模式,则可以使用以下语法组合它们:

(||)

以下a_or_b正则表达式将匹配任何字符或ab字符的字符串:

....

a_or_b = re.compile("(a|b)") if a_or_b.search("a"):

print("'a' is a match") if a_or_b.search("b"):

print("'b' is a match") if a_or_b.search("c"):

print("'c' is a match")

匹配序列而不是仅匹配一个字符

如果+字符位于另一个字符或模式之后,则正则表达式将匹配该模式的任意长序列。这非常有用,因为它可以很容易地表达可以是任意长度的单词或数字。

将模式放在一起

通过一个接一个地组合图案串可以产生更复杂的图案。在下面的示例中,我创建了一个正则表达式,用于搜索严格后跟单词的数字。生成正则表达式的模式字符串由以下内容组成:

与数字序列匹配的模式字符串:[0-9]+与空白字符匹配的模式字符串:s与字母序列匹配的模式字符串:[az] +

与字符串结尾或空格字符匹配的模式字符串:(s | $)

....

number_then_word = re.compile("[0-9]+s[a-z]+(s|$)")

正则表达式split()函数

Python中的 Regex 对象也有一个split()方法。split方法将搜索字符串 拆分 为子字符串数组。所述 分裂 发生在沿着其中该图案被识别的字符串中的每个位置。结果是在模式的实例之间出现的字符串数组。如果模式出现在搜索字符串的开头或结尾,则分别在结果数组的开头或结尾包含一个空字符串:

....

print(a_or_b.split("123a456b789")) print(a_or_b.split("a1b"))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK