一文搞定正则表达式,第1张

正则表达式 (Regex) 在文本数据中用于匹配模式。它们用于查找字符串或字符串集合中的特定模式。它们也可用于搜索(查找)、更改和修改文本数据。它们还可用于验证用户输入,例如电子邮件地址和电话号码。

我们需要导入re module以在 python 中使用正则表达式。


正则表达式语法

在我们进入语法之前,我们必须了解正则表达式是一种语言。它有自己的语法和规则。
Regex 存在于 Python 和其他编程语言中,如 Java、C、JavaScript、PHP 等。因此,如果您在这些语言中的任何一种中使用过 Regex,您会发现语法是相同的。

以下是构成正则表达式的一些最常见的语法:

. - 除换行符外的任何字符

^ - 字符串的开始

$ - 字符串结尾

* - 前面的字符出现 0 次或多次

+ - 前面的字符出现 1 次或多次

?- 前面的字符出现 0 次或 1 次

{3} - 正好出现 3 次前面的字符

{3,4} - 前面的字符出现 3 到 4 次

{3,} - 前面的字符出现 3 次或更多次

[az] - 任何小写字母

[AZ] - 任何大写字母

[0-9] - 任何数字

[0-9a-zA-Z] - 任何字母数字字符(上述 3 种语法的组合)

[aeiou] - 任何元音

[^aeiou] - 任何非元音字母(与 [aeiou] 相反)

[0-9]{3} - 任何 3 位数字

[0-9]{3,4} - 任何 3 或 4 位数字

[a-zA-Z]{8} - 任意 8 个字母的单词

[a-zA-Z]{8,} - 任何包含 8 个或更多字母的单词

\w - 任何字母数字字符

\w+ - 任何字母数字字符后跟 1 个或多个字母数字字符

\W - 任何非字母数字字符(与 \w 相反)

\s - 任何空白字符

\S - 任何非空白字符(与 \s 相反)

\d - 任何数字

\D - 任何非数字(与 \d 相反)

\b - 任何单词边界

\B - 任何非单词边界


正则表达式函数/方法

re.compile()- 返回一个正则表达式模式对象,可用于匹配模式的所有出现

re.match()- 如果文本与模式匹配,则返回一个匹配对象

re.search()- 如果文本中的任何地方都存在匹配项,则返回一个匹配对象

re.findall()- 返回包含所有匹配项的字符串列表

re.split()- 返回一个字符串列表,其中字符串在每次匹配时被拆分

re.sub()- 用字符串替换一个或多个匹配项

正则表达式标志

re.I- 忽略大小写(大写和小写)

re.M- 多行(换行)

re.S- 点匹配所有(换行符)

re.U- unicode(仅限 Python 3)

re.X- 冗长(忽略空格和注释)


例子import re
'''The search() method returns a match object if there is a match anywhere in the string. If there is more than one match, only the first occurrence of the match will be returned.'''
string = 'The quick brown fox jumps over the lazy dog.'search = re.search(r'fox', string, re.I) # r - raw string
print(search) # re.Match object; span=(16, 19), match='fox'
print(search.span()) # (16, 19) # returns a tuple containing the start-, and end positions of the match.
print(search.start()) # 16 # returns the start position of the match.
print(search.end()) # 19 # returns the end position of the match.
print(search.group()) # fox # returns the part of the string where there was a match. This is more useful when there's multiple searches.
print(re.search('Fox', string)) # None # returns None if no match was found.
'''The compile() method returns a regex pattern object, which can be used to match all occurrences of a pattern.'''
pattern = re.compile('fox')
print(pattern.search(string)) # re.Match object; span=(16, 19), match='fox'
'''The findall() method returns a list of strings containing all matches.
'''
print(pattern.findall(string))
'''The match() method returns a match object if the text matches the pattern. If there is more than one match, only the first occurrence of the match will be returned.
'''
print(pattern.match(string)) # None # returns None if no match was found.正则表达式字符

.- 任何字符(换行符除外)

\d- 数字 (0-9)

\D- 不是数字 (0-9)

\w- 单词字符(az、AZ、0-9、_)- 任何字母数字字符


例子
string = 'Hey how are you!'pattern = re.compile(r'([a-zA-Z]).([a])') # r - raw string # . - any character except newline # () - capturing group # [a-zA-Z] - any lowercase letter or uppercase letter # [a] - any vowel
search_re = pattern.search(string)print(search_re.group())
# More Examples# 1. Validate email address using regex
pattern = re.compile(r'([a-zA-Z0-9.-]+)@([a-zA-Z-]+)\.([a-zA-Z]{2,5})')email = 'thisisjustatestemail@gmail.com'valid_email = pattern.search(email)print(valid_email.group())


# 2. Validate phone number using regex
pattern = re.compile(r'([0-9]{3})-([0-9]{3})-([0-9]{4})')phone_number = '234-904-112-0034'valid_phone_number = pattern.search(phone_number)print(valid_phone_number.group())

# 3. Validate password using regex (password must be at least 8 characters long)
password = 'Passw@#12!ord'pattern = re.compile(r'[A-Za-z0-9@#$% !]{8,}')
'''- fullmatch() - returns a match object if the string matches the pattern'''
try:valid_password = pattern.fullmatch(password)print(valid_password.group())except AttributeError:print('Invalid password. Password must be at least 8 characters long')

# 4. Validate URL using regex
url = ''pattern = re.compile(r'https?://(www\.)?(\w+)(\.\w+)') # ? - optional # \ - escape character # \w - any alphanumeric character # \. - any period charactervalid_url = pattern.fullmatch(url)valid_url2 = pattern.search(url)print(valid_url.group())print(valid_url2.group())

本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 一文搞定正则表达式

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情