Ticket #3733: text-smart-split.patch
File text-smart-split.patch, 1.5 KB (added by , 18 years ago) |
---|
-
django/utils/text.py
186 186 187 187 smart_split_re = re.compile('("(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'|[^\\s]+)') 188 188 def smart_split(text): 189 """189 r""" 190 190 Generator that splits a string by spaces, leaving quoted phrases together. 191 191 Supports both single and double quotes, and supports escaping quotes with 192 192 backslashes. In the output, strings will keep their initial and trailing 193 193 quote marks. 194 >>> list(smart_split('This is "a person\'s" test.')) 195 ['This', 'is', '"a person\'s"', 'test.'] 194 >>> list(smart_split(r'''This is "a person" test.''')) 195 ['This', 'is', '"a person"', 'test.'] 196 >>> print list(smart_split(r'''This is "a person's" test.'''))[2] 197 "a person's" 198 >>> print list(smart_split(r'''This is "a person\"s" test.'''))[2] 199 "a person"s" 200 >>> list(smart_split('''"a 'one''')) 201 ['"a', "'one"] 202 >>> print list(smart_split(r'''all friends' tests'''))[1] 203 friends' 196 204 """ 205 197 206 for bit in smart_split_re.finditer(text): 198 207 bit = bit.group(0) 199 if bit[0] == '"' :208 if bit[0] == '"' and bit[-1] == '"': 200 209 yield '"' + bit[1:-1].replace('\\"', '"').replace('\\\\', '\\') + '"' 201 elif bit[0] == "'" :210 elif bit[0] == "'" and bit[-1] == "'": 202 211 yield "'" + bit[1:-1].replace("\\'", "'").replace("\\\\", "\\") + "'" 203 212 else: 204 213 yield bit