1 # Regular expression subroutines:
2 # sub(pat, repl, str): replace first occurrence of pattern in string
3 # gsub(pat, repl, str): replace all occurrences of pattern in string
4 # split(str, pat, maxsplit): split string using pattern as delimiter
5 # splitx(str, pat, maxsplit): split string using pattern as delimiter plus
12 # Replace first occurrence of pattern pat in string str by replacement
13 # repl. If the pattern isn't found, the string is returned unchanged.
14 # The replacement may contain references \digit to subpatterns and
15 # escaped backslashes. The pattern may be a string or an already
18 def sub(pat
, repl
, str):
20 if prog
.search(str) >= 0:
23 str = str[:a
] + expand(repl
, regs
, str) + str[b
:]
27 # Replace all (non-overlapping) occurrences of pattern pat in string
28 # str by replacement repl. The same rules as for sub() apply.
29 # Empty matches for the pattern are replaced only when not adjacent to
30 # a previous match, so e.g. gsub('', '-', 'abc') returns '-a-b-c-'.
32 def gsub(pat
, repl
, str):
37 while prog
.search(str, start
) >= 0:
40 if a
== b
== start
and not first
:
41 if start
>= len(str) or prog
.search(str, start
+1) < 0:
45 new
= new
+ str[start
:a
] + expand(repl
, regs
, str)
48 new
= new
+ str[start
:]
52 # Split string str in fields separated by delimiters matching pattern
53 # pat. Only non-empty matches for the pattern are considered, so e.g.
54 # split('abc', '') returns ['abc'].
55 # The optional 3rd argument sets the number of splits that are performed.
57 def split(str, pat
, maxsplit
= 0):
58 return intsplit(str, pat
, maxsplit
, 0)
60 # Split string str in fields separated by delimiters matching pattern
61 # pat. Only non-empty matches for the pattern are considered, so e.g.
62 # split('abc', '') returns ['abc']. The delimiters are also included
64 # The optional 3rd argument sets the number of splits that are performed.
67 def splitx(str, pat
, maxsplit
= 0):
68 return intsplit(str, pat
, maxsplit
, 1)
70 # Internal function used to implement split() and splitx().
72 def intsplit(str, pat
, maxsplit
, retain
):
77 while prog
.search(str, next
) >= 0:
85 res
.append(str[start
:a
])
89 splitcount
= splitcount
+ 1
90 if (maxsplit
and (splitcount
>= maxsplit
)):
92 res
.append(str[start
:])
96 # Capitalize words split using a pattern
98 def capwords(str, pat
='[^a-zA-Z0-9_]+'):
100 words
= splitx(str, pat
)
101 for i
in range(0, len(words
), 2):
102 words
[i
] = string
.capitalize(words
[i
])
103 return string
.joinfields(words
, "")
106 # Internal subroutines:
107 # compile(pat): compile a pattern, caching already compiled patterns
108 # expand(repl, regs, str): expand \digit escapes in replacement string
111 # Manage a cache of compiled regular expressions.
113 # If the pattern is a string a compiled version of it is returned. If
114 # the pattern has been used before we return an already compiled
115 # version from the cache; otherwise we compile it now and save the
116 # compiled version in the cache, along with the syntax it was compiled
117 # with. Instead of a string, a compiled regular expression can also
123 if type(pat
) <> type(''):
124 return pat
# Assume it is a compiled regex
125 key
= (pat
, regex
.get_syntax())
126 if cache
.has_key(key
):
127 prog
= cache
[key
] # Get it from the cache
129 prog
= cache
[key
] = regex
.compile(pat
)
138 # Expand \digit in the replacement.
139 # Each occurrence of \digit is replaced by the substring of str
140 # indicated by regs[digit]. To include a literal \ in the
141 # replacement, double it; other \ escapes are left unchanged (i.e.
142 # the \ and the following character are both copied).
144 def expand(repl
, regs
, str):
152 if c
<> '\\' or i
>= len(repl
):
157 a
, b
= regs
[ord(c
)-ord0
]
166 # Test program, reads sequences "pat repl str" from stdin.
167 # Optional argument specifies pattern used to split lines.
176 if sys
.stdin
.isatty(): sys
.stderr
.write('--> ')
177 line
= sys
.stdin
.readline()
179 if line
[-1] == '\n': line
= line
[:-1]
180 fields
= split(line
, delpat
)
182 print 'Sorry, not three fields'
183 print 'split:', `fields`
185 [pat
, repl
, str] = split(line
, delpat
)
186 print 'sub :', `
sub(pat
, repl
, str)`
187 print 'gsub:', `
gsub(pat
, repl
, str)`