Python USES regular expressions to implement text substitution methods
- 2020-05-30 20:29:21
- OfStack
This article demonstrates how Python USES regular expressions for text substitution. I will share it with you for your reference as follows:
In a sense, 2D client programming is material organization, so picture material organization often needs batch processing,python1 must be the best choice, whether win/linux/mac has a simple operating environment
Take two application scenarios:
Insert the folder name into the front if it is not in a folder
All filename names with a prefix
Just look at the code:
# encoding: UTF-8
import re
# Compiles the regular expression into Pattern object
p = re.compile(r'(?P<folder>(\w+/)*)(?P<filename>\w+\.png)')
# use Pattern Matches the text, gets the match result, and is returned when it fails to match 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 Get 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 s
def f2(m2):
d = m2.groupdict()
return d['folder']+'the_'+d['filename']
print p.sub(f2, the_str)
There are a few things to explain about regular expressions
. python's regular expression is used if the capture requires grouping (? P < named > Matching regular expressions)
re.compile is used to compile regular expressions and return objects
p.finditer returns all matching iterators
p.sub passes the match into the callback function and replaces the text with the return value
. m.groupdict, you can use the group name of the rules to take the corresponding value
PS: here are two more handy regular expression tools for you to use:
JavaScript regular expression online testing tool:
http://tools.ofstack.com/regex/javascript
Online regular expression generation tool:
http://tools.ofstack.com/regex/create_reg
More about Python related content to view this site project: the Python regular expression usage summary ", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"
I hope this article is helpful to you Python programming.