Regular expressions re module

Regular Expressions

Shajiao regular expressions? A Matching string content rules.

'''
常用元字符:

^     匹配字符串开始
$     匹配字符串结束
.     匹配除换行符以外的任意字符
\w    匹配字母或数字或下划线
\s    匹配任意空白符
\d    匹配数字
\b    匹配单词的开始或结束

a|b   匹配字符a或字符b
()   匹配括号内的表达式,也表示一个组
[...] 匹配字符组中的字符
'''
#通常情况下,正则表达式中所谓的“单词”,就是由“\w”所定义的字符所组成的子串。
'''
量词:

*      重复零次或多次
+      重复一次或多次
?      重复零次或一次
{n}    重复n次
{n,}   重复n次或更多次
{n, m} 重复n到m次

'''
'''
常用反义词:

\W    匹配任意不是字母、数字、下划线、汉子的字符
\S    匹配任意不是空白符的字符
\D    匹配任意不是数字的字符
\B    匹配不是单词开头或结束的位置
[^x]  匹配不是x的任意字符串
[^ae]    匹配除了ae这几个字母以外的任意字符
'''

(), [], {} Distinction:

() Is a plurality of matching, the process as a set in brackets. (Ab) there is a string that represents the character to match such ab. Matching string, often with | (or) with use.

[] Is a single match, [ABC], if a single character is represented by a, b, c a, the match is successful. Special characters in [], is an ordinary character.

{} Is the number of matches

Key: *, + ,? are all greedy matching, matching is possible, followed by a plus sign so that it becomes inert match?

Regular on match are greedy match (try to match the multi-point)

In the back by adding a quantifier?, It can become a greedy match non-greedy match (inert match)

example:

  On behalf of the match string: I am Marshal ratio

  Regular: I -> I was.

   I * -> I was Commander in Chief than

      I ? -> I: Note that matches zero or more, followed by the addition of a quantifier? Become non-greedy match, so the number. Is 0, the result for me.

      .? I + -> I Description: + match one or more, plus become inert match, only match a minimum of?. The result is I am.

     I ?? -> Likewise, behind the quantifier, it is zero or one.?. Press 0 minimum to count.

例题:
匹配身份证号
^[1-9]\d{16}[1-9x]|[1-9]\d{14}$
匹配手机号:
^(13|15|16|17|18)\d{9}$
匹配邮箱:
^\w+@\w+\.\w+$

Escapes

Sometimes there will be a string of special characters, with the character of the conflict metacharacters, this time you need to use the escape character, for example, want to match the string \ n, you need to \ n. If the character is to be matched '\ n', then being compared: \\ n

几个常用的非贪婪匹配Pattern
*? 重复任意次,但尽可能少重复
+? 重复1次或更多次,但尽可能少重复
?? 重复0次或1次,但尽可能少重复
{n,m}? 重复n到m次,但尽可能少重复
{n,}? 重复n次以上,但尽可能少重复
.*?的用法
. 是任意字符
* 是取 0 至 无限长度
? 是非贪婪模式。
何在一起就是 取尽量少的任意字符,一般不会这么单独写,他大多用在:
.*?x

就是取前面任意长度的字符,直到一个x出现

Regular expansion:

(pattern) 匹配pattern并获取这一匹配。所获取的匹配可以从产生的Matches集合得到,在VBScript中使用SubMatches集合,在JScript中则使用$0…$9属性。要匹配圆括号字符,请使用“(”或“)”。

(?:pattern) 匹配pattern但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用或字符“(|)”来组合一个模式的各个部分是很有用。例如“industr(?:y|ies)”就是一个比“industry|industries”更简略的表达式。

(?=pattern) 正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,“Windows(?=95|98|NT|2000)”能匹配“Windows2000”中的“Windows”,但不能匹配“Windows3.1”中的“Windows”。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。

(?!pattern) 正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如“Windows(?!95|98|NT|2000)”能匹配“Windows3.1”中的“Windows”,但不能匹配“Windows2000”中的“Windows”。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始

re module

re.findall()

import re

res = re.findall('a', 'assbdfasafqsd')
print(res)

>>> ['a', 'a', 'a']

说明:返回所有满足正则匹配的结果,放在列表里

findall of priority query:

import re

ret = re.findall('www.(baidu|oldboy).com', 'www.oldboy.com')
print(ret)  # ['oldboy']     这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可

ret = re.findall('www.(?:baidu|oldboy).com', 'www.oldboy.com')
print(ret)  # ['www.oldboy.com']

re.search()

res = re.search('c', 'adfasdfasdf')
print(res.group())

>>> AttributeError: 'NoneType' object has no attribute 'group'

res = re.search('a', 'adfasdfasdf')
print(res.group())

>>> a

说明:re.search,会在整个字符串内查找,但只会返回第一个匹配。
        如果没有匹配,就会返回None。
        如果有匹配,返回第一个匹配,是一个包含匹配信息的对像。该对象调用.group(),才会返回值。

Extended:

ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
#还可以在分组中利用?<name>的形式给分组起名字
#获取的匹配结果可以直接用group('名字')拿到对应的值
print(ret.group('tag_name'))  #结果 :h1
print(ret.group())  #结果 :<h1>hello</h1>

ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
#如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致
#获取的匹配结果可以直接用group(序号)拿到对应的值
print(ret.group(1))
print(ret.group())  #结果 :<h1>hello</h1>

re.match()

res = re.match('a', 'abc')
print(res.group())

>>> a

res = re.match('a', 'bac')
print(res.group())

>>> AttributeError: 'NoneType' object has no attribute 'group'

res = re.match('ba', 'bac')
print(res.group())

>>> ba

说明:re.match只会在字符串开头匹配。
        如果字符串开始没匹配到,就会返回一个None。

**** Key: **

The same point re.match () with re.search (), the differences:

match method, from the beginning of the string match, if not matched to the start, None is returned.

The search method is to match the entire string in a regular, there is a match, the first matching object is returned. There is no match, return None.

When the match and the match is successful search, no matter how many can match the success, only to return the first matching object.

No match, returns None.

The matching is successful, we need to call .group () method takes a value matching.

re.split()

ret = re.split('我', '我是大帅比')
print(ret)
>>>  ['', '是大帅比']

ret = re.split('是', '我是大帅比')
print(ret)
>>> ['我', '大帅比']

ret = re.split('比', '我是大帅比')
print(ret)
>>> ['我是大帅', '']

ret = re.split('我|比', '我是大帅比')
print(ret)
>>> ['', 是大帅', '']

ret = re.split('是|帅', '我是大帅比')
print(ret)
>>> ['我', '大', '比']

split the priority query

ret=re.split("\d+","eva3egon4yuan")
print(ret) #结果 : ['eva', 'egon', 'yuan']

ret=re.split("(\d+)","eva3egon4yuan")
print(ret) #结果 : ['eva', '3', 'egon', '4', 'yuan']

#在匹配部分加上()之后所切出的结果是不同的,
#没有()的没有保留所匹配的项,但是有()的却能够保留了匹配的项,
#这个在某些需要保留匹配部分的使用过程是非常重要的。

re.sub

ret = re.sub('\d', 'H', 'eva3egon4yuan4', 2)#将数字替换成'H',参数2表示只替换2个
print(ret) 
>>> evaHegonHyuan4

ret = re.sub('[^\d]', 'H', 'eva3egon4yuan4')
print(ret)
>>>HHH3HHHH4HHHH4

re.subn

ret = re.subn('\d', 'H', 'eva3egon4yuan4')#将数字替换成'H',返回元组(替换的结果,替换了多少次)
print(ret)

>>> ('evaHegonHyuan4', 2)

re.compile

obj = re.compile('\d{3}')  #将正则表达式编译成为一个 正则表达式对象,规则要匹配的是3个数字
ret = obj.search('abc123eeee') #正则表达式对象调用search,参数为待匹配的字符串
print(ret.group())  #结果 : 123

re.finditer

import re
ret = re.finditer('\d', 'ds3sy4784a')   #finditer返回一个存放匹配结果的迭代器
print(ret)  # <callable_iterator object at 0x10195f940>
print(next(ret).group())  #查看第一个结果
print(next(ret).group())  #查看第二个结果
print([i.group() for i in ret])  #查看剩余的左右结果

>>><callable_iterator object at 0x10d857a50>
>>>3
>>>4
>>>['7', '8', '4']

Guess you like

Origin www.cnblogs.com/KbMan/p/11203912.html