Text in python (2 ),
This article mainly records and summarizes the learning and understanding of this chapter in the Python standard library.
In Python, some methods such as text are particularly common. In general, a class such as String is used, which should be the most basic standard class in Python.
1.3.6 match with Group Resolution
Match. groups () returns a string sequence in the order of the group in which the expression matches the string.
You can use group () to obtain a group match.
# Group resolution text = 'this is a text -- with punctuation. 'print 'input text: ', text regex = re. compile (R' (\ bt \ w +) \ W + (\ w +) ') print 'pattern:', regex. pattern match = regex. search (text) print 'entire match: ', match. group (0) print 'word starting with t: ', match. group (1) print 'word after t Word: ', match. group (2)
Python expands the syntax of the basic group and adds the named group ). The Group is indicated by the name, which makes it easier to modify the mode without having to modify the code that matches the result at the same time.
Syntax :(? P <name> pattern)
# Name group print '-' * 30 for pattern in [R' ^ (? P <first_word> \ w +) ', R '(? P <last_word> \ w +) \ S * $ ', R '(? P <t_word> \ bt \ w +) \ W + (? P <other_word> \ w +) ', R '(? P <ends_with_t> \ w + t) \ B ']: regex = re. compile (pattern) match = regex. search (text) print 'matching "% s" '% pattern print '', match. groups () print '', match. groupdict () print '\ N'
You can use groupdict () to obtain a dictionary, which maps group names to matched substrings.
# Updated test_pattern () print '-' * 30 def test_pattern (text, patterns = []): "Given the source text and a list of patters, look for matches for each pattern within the text and print them to stdout. "# look for each pattern in the text and print the results for pattern, desc in patterns: print 'pattern % r (% s) \ n' % (pattern, desc) print '% R' % text for match in re. finditer (pattern, text): s = match. start () e = match. end () prefix = ''* (s) print '% s % r % s' % (prefix, text [s: e],'' * (len (text) -e) print match. groups () if match. groupdict (): print '% s % s' % (''* (len (text)-s), match. groupdict () print return test_pattern ('abababbba ', [(r'a (a *) (B *))', 'A followed by 0-n a and 0-n B '),])