This article mainly introduces the method that Python uses regular expression to implement text substitution, analyzes the specific operation steps of Python using regular expression to realize text substitution with the example form, and the related usage precautions, the friend who need can refer to the following
Three-way client programming in a sense is the material organization, so, the picture material organization often need batch processing, Python must be the best choice, regardless of Win/linux/mac has a simple running environment
Two application Scenarios :
① if it is not in a folder, insert the folder name in front
② all filename names plus a prefix
Look directly at the code:
# Encoding:utf-8import re# compiles the regular expression into the pattern object P = Re.compile (R ' (? P<folder> (\w+/) *) (? p<filename>\w+\.png) ' # matches the text using pattern, gets the match result, cannot match when will return None#match = Pattern.match (' <key>xxx/ Duobaojiemian_l/yangpizi.png</key> ') The_str = "" "<key>xxxx/duobaojiemian2222_l/duobaojiemian_l/ yangpizi.png</key> <key>yangpizi2.png</key> <key>yangpizi3.png</key> "" "for M in P.finditer (THE_STR): # Use Match to get Group Info print m.groupdict () print '-------------------------------' #f = Lambda m:m.group () . Find (' xxxx/') = =-1 and ' xxxx/' +m.group () or M.group () def f (m): s = M.group () return S.find (' xxxx/') = =-1 and ' xxxx/' +s or sdef F2 (m2): D = m2.groupdict () return d[' folder ']+ ' the_ ' +d[' filename ']print p.sub (F2, THE_STR)
There are several questions about regular expressions that need to be accounted for.
①. Python Regular Expressions Use this syntax if the capture requires grouping (? p< naming > matching regular expressions)
②. Re.compile to compile a regular expression and return an object
③. P.finditer returns all matching iterators
④. P.sub passes a match to the callback function and replaces the text with the return value
⑤. M.groupdict, you can use the group name to take the corresponding value