Regular expressions function abbreviated

A function of regular expressions: re module: module regular expressions: a regular expression had correlation function is introduced into the package.

1) re.match function: try to match a pattern from a starting position of the string, the matching is successful returns a matching object. If the starting position of the match is unsuccessful, match () returns None.
Syntax: re.match (pattern, string, flags = 0)

2) re.search Method: scanning the entire first string and returns a successful match.

Syntax: re.search (pattern, string, flags = 0)

Analytical parameters:
  . 1, pattern: regular expressions matching;
  2, String: string to match;
  . 3, the flags: Flag bits (optional), for controlling the regular expression matching mode, as is case sensitive, multi-line matches, and so on.

  Optional flags:
    re.I: making case-insensitive matching
    re.L: localizing a recognition (locale-aware) matching
    re.M: multi-line matching, and impact ^ $
    re.S: that the matching line comprises a transducer. including all the characters
    re.U: According to parse character Unicode character set. This flag affect \ w, \ W, \ b, \ B.
    Re.X: This flag by giving you more flexibility in format so that you will write regular expressions easier to understand.

These two functions are very similar, but there are differences: re.match match only the beginning of the string, if the string does not conform to begin regular expression, the match fails, the function returns None; and re.search match the entire string, until you find a match.
Such as:

  >>>import re
  >>>line = "123abc456"  
  >>>matchobj = re.match("abc",line)
  >>>matchobj1 = re.search("abc",line)
  >>>if matchobj:
  >>>  print (matchobj.group(0))
  >>>else:
  >>>  print("No match!")
  >>>if matchobj1:
  >>>  print (matchobj1.group(0))
  >>>else:
  >>>  print("No match!")
输出:
  >>>  No match!
  >>>  abc

Further, the regular expression matching process, Group () is used to raise the string intercepted packets, the regular expression in the '()' is used to indicate the packet.

Such as:
  >>> Import Re
  >>> = Line "123abc456"
  >>> matchobj re.match = ( "([0-9] *) ([AZ] *) ([0-9] *)", Line )
  >>> IF matchobj:
  >>> Print matchobj.group (0) {# returns 123abc456 group () with the group (0) is the entire regular expression matching results]
  >>> print matchobj.group (1) # 123 returns [group (1) listed in the first parenthesis matching section]
  >>> print matchobj.group (2) # returns abc [group (2) listed in the second bracket matching section]
  >>> print matchobj.group (3 ) returns # 456 [group (3) listed in the third section matching brackets. ]
  >>> the else:
  ( "! No match") >>> Print [no successful match, re.search () returns None]

备注: 1、start([group]) 方法用于获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引),参数默认值为 0;
    2、end([group]) 方法用于获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1),参数默认值为 0;
    3、span([group]) 方法返回 (start(group), end(group))。

 

3)re.sub:用于替换字符串中的匹配项。

语法:re.sub(pattern, repl, string, count=0, flags=0)

参数解析:前3个参数为必选参数,后面两个为可选。
  1、pattern : 正则中的模式字符串。
  2、repl : 替换的字符串,也可为一个函数。
备注{
  当repl为函数时,如:将字符串中的匹配的数字乘以2:
  >>>import re
  >>>def double(matched):
  >>>  value = int(matched.group('value'))
  >>>  return str(value * 2)
  >>>s = 'A23G4HFD567'
  #(?<name>exp):匹配exp,并捕获文本到名称为name的组里,也可以写成 (?'name'exp)。但是在Python中,为(?P<name>exp)。
  >>>print(re.sub('(?P<value>\d+)',double,s))
  }
  3、string : 要被查找替换的原始字符串。
  4、count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
  5、flags : 编译时用的匹配模式,数字形式。
如:
  >>>import re
  >>>number = "2019-12-28 #这是一个日期
  # 删除注释
  >>>num = re.sub(r'#.*$', "", number)#r声明后面的字符串为原始字符串,防止计算机将'\'理解为转义字符.
  >>>print("日期为 : ", num)
  # 移除非数字的内容
  >>>num = re.sub(r'\D', "", number)
  >>>print("日期为 : ", num)
  #将中国格式改为美国格式:2019-12-28转为12/28/2019
  #用()来划定原字符串的组,{}中表示数字的个数,2,3,1为输入的字符串三段的序号
  >>>num = re.sub('(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1',number)
  >>>print("日期为 : ", num)
输出:
  日期为 : 2019-12-28
  日期为 : 20191228
  日期为 : 12/28/2019

 

关于正则表达式中会出现的\1,\2这样的一个解释:举个例子:假如文本有个单纯重复了 2 次,利用正则保留一个输出:
  >>> import re
  >>> x='this is is ok ok'
  >>> y= re.sub(r'(\w+)\s\1',r'\1',x)
  >>> print(y) #输出:this is ok
解析:\1是匹配第一个分组匹配到的内容,也就是所谓的\1引用了第一个()匹配到的内容。具体到这个例子:(\w+)匹配一个单词,\s匹配空白字符,\1引用了第一个匹配到的内容:一个单词,综合起来就是用'第一个匹配到的内容'去代替'第一个匹配到的内容+空格+第一个匹配到的内容',也就是实现了去掉重复的功能。再往后推:\2\3\4都是一个道理。

 

4)compile函数:用于编译正则表达式,生成一个正则表达式(pattern)对象。供match()和search()这两个函数使用。
语法:re.compile(pattern[,flags])
参数解析:
  1、pattern:一个字符串形式的正则表达式;
  2、flags:可选,表示匹配模式,比如忽略大小写,多行模式等。

编译正则表达式的时候,调用的match()所含的参数跟前面的不一样,来看个例子:
  >>>import re
  >>> pattern = re.compile(r'\d+') # 用于匹配至少一个数字
  >>> m = pattern.match('one12twothree34four') # 查找头部,没有匹配
  >>> print m #输出None
  >>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配【match参数列表跟前面的定义不一样的了】
  >>> print m #输出:None
  >>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
  >>> print m #输出一个match对象


5)findall:在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
注意:match 和 search 是匹配一次; findall 匹配所有。
语法:re.findall(string[, pos[, endpos]])
参数解析:
  1、string:待匹配的字符串。
  2、pos :可选参数,指定字符串的起始位置,默认为 0。
  3、endpos: 可选参数,指定字符串的结束位置,默认为字符串的长度。
例子:
  >>> import re
  >>> pattern = re.compile(r'\d+') # 查找数字
  >>> result1 = pattern.findall('runoob 123 google 456')
     >>> result2 = pattern.findall('run88oob123google456', 0, 10)
  >>> print(result1) #输出:['123', '456']
  >>> print(result2) #输出:['88', '12']


6)re.finditer:和findall类似,在字符串中找到正则表达式所匹配的所有子串,[区别]并把它们作为一个迭代器返回。
语法:re.finditer(pattern, string, flags=0)
参数分析:
  1、pattern:匹配的正则表达式
  2、string:要匹配的字符串。
  3、flags:标志位,可选参数
举例:
  >>> import re
  >>> it = re.finditer(r"\d+","12a32bc43jf3")
  >>> for match in it:
  >>> print (match.group() )
  输出: 12
      32
      43
      3


7)re.split:split 方法按照能够匹配的子串将字符串分割后返回列表。另外,对于一个找不到匹配的字符串而言,split 不会对其作出分割。
语法:re.split(pattern, string[, maxsplit=0, flags=0])
参数解析:
  1、pattern:匹配的正则表达式
  2、string:要匹配的字符串。
  3、maxsplit: 分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。
  4、flags 标志位,可选参数
举例:(注意是否保留匹配项的区别)
  >>> import re
  #不保留匹配项
  >>> m = re.split('\d+' , '123abc321cba')
  >>> print m #输出:[”, ‘abc’, ‘cba’]
  >>> print "\n"
  #保留匹配项
  >>> m = re.split('(\d+)' , '123abc321cba')
  >>> print m #输出:[”, ‘123’, ‘abc’, ‘321’, ‘cba’]

Guess you like

Origin www.cnblogs.com/yangrongkuan/p/12111019.html