Python uses regular expression text substitution

Source: Internet
Author: User

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, but Win/linux/mac have a simple running environment

Two application scenarios:

    • If it is not in a folder, insert the folder name in the previous
    • Add a prefix to all filename names

Just look 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 used to compile a regular expression and return an object
    • P.finditer return all matching iterators
    • P.sub passes the 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

Python uses regular expression text substitution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.