]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | # (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and |
2 | # distribute this software is granted provided this copyright notice appears in | |
3 | # all copies. This software is provided "as is" without express or implied | |
4 | # warranty, and with no claim as to its suitability for any purpose. | |
5 | ||
6 | import re | |
7 | ||
8 | from b2.util import bjam_signature | |
9 | ||
10 | ||
11 | def transform (list, pattern, indices = [1]): | |
92f5a8d4 | 12 | """ Matches all elements of 'list' against the 'pattern' |
7c673cae | 13 | and returns a list of the elements indicated by indices of |
92f5a8d4 TL |
14 | all successful matches. If 'indices' is omitted returns |
15 | a list of first paranthethised groups of all successful | |
7c673cae FG |
16 | matches. |
17 | """ | |
18 | result = [] | |
19 | ||
20 | for e in list: | |
21 | m = re.match (pattern, e) | |
22 | ||
23 | if m: | |
24 | for i in indices: | |
25 | result.append (m.group (i)) | |
26 | ||
27 | return result | |
28 | ||
29 | ||
30 | @bjam_signature([['s', 'pattern', 'replacement']]) | |
31 | def replace(s, pattern, replacement): | |
32 | """Replaces occurrences of a match string in a given | |
33 | string and returns the new string. The match string | |
34 | can be a regex expression. | |
35 | ||
36 | Args: | |
37 | s (str): the string to modify | |
38 | pattern (str): the search expression | |
39 | replacement (str): the string to replace each match with | |
40 | """ | |
41 | # the replacement string may contain invalid backreferences (like \1 or \g) | |
42 | # which will cause python's regex to blow up. Since this should emulate | |
43 | # the jam version exactly and the jam version didn't support | |
44 | # backreferences, this version shouldn't either. re.sub | |
45 | # allows replacement to be a callable; this is being used | |
46 | # to simply return the replacement string and avoid the hassle | |
47 | # of worrying about backreferences within the string. | |
48 | def _replacement(matchobj): | |
49 | return replacement | |
50 | return re.sub(pattern, _replacement, s) | |
51 | ||
52 | ||
53 | @bjam_signature((['items', '*'], ['match'], ['replacement'])) | |
54 | def replace_list(items, match, replacement): | |
55 | """Replaces occurrences of a match string in a given list of strings and returns | |
56 | a list of new strings. The match string can be a regex expression. | |
57 | ||
58 | Args: | |
59 | items (list): the list of strings to modify. | |
60 | match (str): the search expression. | |
61 | replacement (str): the string to replace with. | |
62 | """ | |
63 | return [replace(item, match, replacement) for item in items] |