This article mainly introduces the method of Python using regular expressions to achieve text replacement. It analyzes the specific steps and related usage precautions of Python using regular expressions to implement text replacement in the form of examples. Friends in need can refer to the following
2D client programming is material organization in a sense. Therefore, image material organization often requires batch processing. Python must be the best choice. Whether it is win/linux/mac, it has a simple operating environment.
Two application scenarios:
① If it is not in a folder, insert the folder name in front
② Add a prefix
to all file names. Let’s look at the code directly:
# encoding: UTF-8 import re # 将正则表达式编译成Pattern对象 p = re.compile(r'(?P<folder>(\w+/)*)(?P<filename>\w+\.png)') # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回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): # 使用Match获得分组信息 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 s def f2(m2): d = m2.groupdict() return d['folder']+'the_'+d['filename'] print p.sub(f2, the_str)
There are several things that need to be explained about regular expressions
①. If the capture of Python's regular expression requires grouping, use this syntax (?P
②. re.compile is used to compile the regular expression and return the object
③. p.finditer returns all matching iterators
④. p.sub passes the matching items into the callback function and replaces the text with the return value
⑤. m.groupdict, you can use the group naming to get the corresponding value
The above is the detailed content of Examples of text replacement using regular expressions in Python. For more information, please follow other related articles on the PHP Chinese website!