This article mainly introduces Python's method of using regular expressions to replace text, and analyzes the specific steps and precautions for using regular expressions to replace text in Python based on examples, for more information about how to use regular expressions to replace text in Python, this article analyzes the specific operation steps and precautions for using regular expressions to replace text in Python based on examples. For more information, see
In a sense, 2D client programming is the material organization. Therefore, image material organization often needs batch processing. python must be the best choice, both Windows, linux, and mac have a simple running environment.
Here are two examples:Application scenarios:
① If it is not in a folder, insert the folder name to the front.
② Add a prefix to all file names
Check the code directly:
# Encoding: UTF-8import re # compile the regular expression into the Pattern object p = re. compile (r '(? P
(\ W + /)*)(? P
\ W + \. png) ') # use Pattern to match the text and obtain the matching result. if the match fails, None is returned. # match = pattern. match ('
Xxx/duobaojiemian_L/yangpizi.png
') The_str = """
XXXX/duobaojiemian2222_L/duobaojiemian_L/yangpizi.png
Yangpizi2.png
Yangpizi3.png
"For m in p. finditer (the_str): # Use Match to obtain the group information 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 elements to explain about a regular expression.
①. If the python regular expression is captured and needs to be grouped, use this syntax (? P <命名> Matched regular expression)
②. Re. compile is used to compile regular expressions and return objects.
③. P. finditer returns all matching iterators
④. P. sub transfers the matching item to the callback function and replaces the text with the return value.
⑤. M. groupdict. you can use the group name to obtain the corresponding value.
The above is the detailed content of the example that uses regular expressions to replace text in Python. For more information, see other related articles in the first PHP community!