blob: 2b044b636ac22a3e967af2fee96ca22af316ffa2 [file] [log] [blame]
Guido van Rossumf81e5b91997-10-23 22:43:50 +00001#! /usr/bin/env python1.5
2
3"""Convert old ("regex") regular expressions to new syntax ("re").
4
5When imported as a module, there are two functions, with their own
6strings:
7
8 convert(s, syntax=None) -- convert a regex regular expression to re syntax
9
10 quote(s) -- return a quoted string literal
11
12When used as a script, read a Python string literal (or any other
13expression evaluating to a string) from stdin, and write the
14translated expression to stdout as a string literal. Unless stdout is
15a tty, no trailing \n is written to stdout. This is done so that it
16can be used with Emacs C-U M-| (shell-command-on-region with argument
17which filters the region through the shell command).
18
19No attempt has been made at coding for performance.
20
21Translation table...
22
23 \( ( (unless RE_NO_BK_PARENS set)
24 \) ) (unless RE_NO_BK_PARENS set)
25 \| | (unless RE_NO_BK_VBAR set)
26 \< \b (not quite the same, but alla...)
27 \> \b (not quite the same, but alla...)
28 \` \A
29 \' \Z
30
31Not translated...
32
33 .
34 ^
35 $
36 *
37 + (unless RE_BK_PLUS_QM set, then to \+)
38 ? (unless RE_BK_PLUS_QM set, then to \?)
39 \
40 \b
41 \B
42 \w
43 \W
44 \1 ... \9
45
46Special cases...
47
48 Non-printable characters are always replaced by their 3-digit
49 escape code (except \t, \n, \r, which use mnemonic escapes)
50
51 Newline is turned into | when RE_NEWLINE_OR is set
52
53XXX To be done...
54
55 [...] (different treatment of backslashed items?)
56 [^...] (different treatment of backslashed items?)
57 ^ $ * + ? (in some error contexts these are probably treated differently)
58 \vDD \DD (in the regex docs but only works when RE_ANSI_HEX set)
59
60"""
61
62
63import regex
64from regex_syntax import * # RE_*
65
66# Default translation table
67mastertable = {
68 r'\<': r'\b',
69 r'\>': r'\b',
70 r'\`': r'\A',
71 r'\'': r'\Z',
72 r'\(': '(',
73 r'\)': ')',
74 r'\|': '|',
75 '(': r'\(',
76 ')': r'\)',
77 '|': r'\|',
78 '\t': r'\t',
79 '\n': r'\n',
80 '\r': r'\r',
81}
82
83
84def convert(s, syntax=None):
85 """Convert a regex regular expression to re syntax.
86
87 The first argument is the regular expression, as a string object,
88 just like it would be passed to regex.compile(). (I.e., pass the
89 actual string object -- string quotes must already have been
90 removed and the standard escape processing has already been done,
91 e.g. by eval().)
92
93 The optional second argument is the regex syntax variant to be
94 used. This is an integer mask as passed to regex.set_syntax();
95 the flag bits are defined in regex_syntax. When not specified, or
96 when None is given, the current regex syntax mask (as retrieved by
97 regex.get_syntax()) is used -- which is 0 by default.
98
99 The return value is a regular expression, as a string object that
100 could be passed to re.compile(). (I.e., no string quotes have
101 been added -- use quote() below, or repr().)
102
103 The conversion is not always guaranteed to be correct. More
104 syntactical analysis should be performed to detect borderline
105 cases and decide what to do with them. For example, 'x*?' is not
106 translated correctly.
107
108 """
109 table = mastertable.copy()
110 if syntax is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 syntax = regex.get_syntax()
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000112 if syntax & RE_NO_BK_PARENS:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000113 del table[r'\('], table[r'\)']
114 del table['('], table[')']
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000115 if syntax & RE_NO_BK_VBAR:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 del table[r'\|']
117 del table['|']
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000118 if syntax & RE_BK_PLUS_QM:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 table['+'] = r'\+'
120 table['?'] = r'\?'
121 table[r'\+'] = '+'
122 table[r'\?'] = '?'
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000123 if syntax & RE_NEWLINE_OR:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 table['\n'] = '|'
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000125 res = ""
126
127 i = 0
128 end = len(s)
129 while i < end:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 c = s[i]
131 i = i+1
132 if c == '\\':
133 c = s[i]
134 i = i+1
135 key = '\\' + c
136 key = table.get(key, key)
137 res = res + key
138 else:
139 c = table.get(c, c)
140 res = res + c
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000141 return res
142
143
144def quote(s, quote=None):
145 """Convert a string object to a quoted string literal.
146
147 This is similar to repr() but will return a "raw" string (r'...'
148 or r"...") when the string contains backslashes, instead of
149 doubling all backslashes. The resulting string does *not* always
150 evaluate to the same string as the original; however it will do
151 just the right thing when passed into re.compile().
152
153 The optional second argument forces the string quote; it must be
154 a single character which is a valid Python string quote.
155
156 """
157 if quote is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000158 q = "'"
159 altq = "'"
160 if q in s and altq not in s:
161 q = altq
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000162 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 assert quote in ('"', "'")
164 q = quote
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000165 res = q
166 for c in s:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 if c == q: c = '\\' + c
168 elif c < ' ' or c > '~': c = "\\%03o" % ord(c)
169 res = res + c
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000170 res = res + q
171 if '\\' in res:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 res = 'r' + res
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000173 return res
174
175
176def main():
177 """Main program -- called when run as a script."""
178 import sys
179 s = eval(sys.stdin.read())
180 sys.stdout.write(quote(convert(s)))
181 if sys.stdout.isatty():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 sys.stdout.write("\n")
Guido van Rossumf81e5b91997-10-23 22:43:50 +0000183
184
185if __name__ == '__main__':
186 main()