Python study notes 9: regular expressions, python Study Notes
This article does not involve the content of regular expressions, but only describes the regular expression usage and common methods in python.
I. re Module
RegEx in python
>>>import re>>>s = r'abc'>>>re.findall(s,'aaaabcaaaaa')['abc']
Or compile first (it will be faster ):
>>> Import re >>> r1 = re. compile (r 'abc', re. i) >>> re. findall (r1, 'abcabd') ['abc'] # or use the following method> r1.findall ('abcabd') ['abc']
Common compilation flag:
Ii. Common Methods
1. compile: compile regular expressions to accelerate the running speed. The usage is as follows:
2. match: determines whether the RE is at the starting position of the string. The returned result is a Match object, but None is not returned.
3. search: scan the string and find the position where the RE matches. The Match object is returned. If no Match is found, None is returned.
4. findall: Find all the substrings matching the RE and return them as the list.
5. finditer: Find all the substrings matching the RE and return them as the iterator. The iterator contains the Match object.
6. sub (regex, replace [can be a function], content, count = 0 [optional, number of replicas, default value: All], flags = 0 [optional, regular parameter, such as re. i): Data replacement
Http://www.crifan.com/python_re_sub_detailed_introduction/
7. subn (regex, replace, content, count = 0, flags = 0): Same as sub, but the return value contains the replacement times.
8. split (string [, maxsplit = 0]): separates strings by regular expressions.
Iii. Common Methods in Match object
1. group (): returns the string matched by the RE.
2. start (): return the starting position of the matching.
3. end (): returns the position at which the matching ends.
4. span (): returns the position where a tuple contains a match (start and end ).
Example:
import rem = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!') print "m.string:", m.stringprint "m.re:", m.reprint "m.pos:", m.posprint "m.endpos:", m.endposprint "m.lastindex:", m.lastindexprint "m.lastgroup:", m.lastgroup print "m.group(1,2):", m.group(1, 2)print "m.groups():", m.groups()print "m.groupdict():", m.groupdict()print "m.start(2):", m.start(2)print "m.end(2):", m.end(2)print "m.span(2):", m.span(2)print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3') ### output #### m.string: hello world!# m.re: <_sre.SRE_Pattern object at 0x016E1A38># m.pos: 0# m.endpos: 12# m.lastindex: 3# m.lastgroup: sign
# m.group(1,2): ('hello', 'world')# m.groups(): ('hello', 'world', '!')# m.groupdict(): {'sign': '!'}# m.start(2): 6# m.end(2): 11# m.span(2): (6, 11)# m.expand(r'\2 \1\3'): world hello!