Home  >  Article  >  Backend Development  >  Examples of text replacement using regular expressions in Python

Examples of text replacement using regular expressions in Python

Y2J
Y2JOriginal
2017-04-21 15:06:141545browse

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&#39;(?P<folder>(\w+/)*)(?P<filename>\w+\.png)&#39;)
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
#match = pattern.match(&#39;<key>xxx/duobaojiemian_L/yangpizi.png</key>&#39;)
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 &#39;-------------------------------&#39;
#f = lambda m: m.group().find(&#39;XXXX/&#39;) == -1 and &#39;XXXX/&#39;+m.group() or m.group()
def f(m):
 s = m.group()
 return s.find(&#39;XXXX/&#39;) == -1 and &#39;XXXX/&#39;+s or s
def f2(m2):
 d = m2.groupdict()
 return d[&#39;folder&#39;]+&#39;the_&#39;+d[&#39;filename&#39;]
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 (?P8a11bc632ea32a57b3e3693c7987c420matching regular expression)

②. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn