Regular expressions in python have a feature called symbolic group names.
If you use this, you can name and manage the matched substrings, so it will be more readable than using \ 1
.
The following is an example.
# encoding: utf-8
import re
testtext = 'abcdefghijklmnopqrstuvwxyz'
pattern = re.compile(r'.*(?P<test1>k.*t).*')
m = pattern.match(testtext)
if m:
print(m.group('test1'))
After all, when the form (? P <name> regular expression)
appears in a regular expression,
The part that matches the specified regular expression can be retrieved later with the name specified by the group
method.
Also, the equivalent function in ruby
/.*(?<test1>k.*t).*/ =~ 'abcdefghijklmnopqrstuvwxyz'
p test1
is. In the case of ruby, it is automatically expanded to a variable. I think I like it.
Recommended Posts