| Total Complexity | 6 |
| Total Lines | 41 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | def clean_regex(regex): |
||
| 2 | """ |
||
| 3 | Escape any regex special characters other than alternation. |
||
| 4 | |||
| 5 | :param regex: regex from datatables interface |
||
| 6 | :type regex: str |
||
| 7 | :rtype: str with regex to use with database |
||
| 8 | """ |
||
| 9 | # copy for return |
||
| 10 | ret_regex = regex |
||
| 11 | |||
| 12 | # these characters are escaped (all except alternation | and escape \) |
||
| 13 | # see http://www.regular-expressions.info/refquick.html |
||
| 14 | escape_chars = '[^$.?*+(){}' |
||
| 15 | |||
| 16 | # remove any escape chars |
||
| 17 | ret_regex = ret_regex.replace('\\', '') |
||
| 18 | |||
| 19 | # escape any characters which are used by regex |
||
| 20 | # could probably concoct something incomprehensible using re.sub() but |
||
| 21 | # prefer to write clear code with this loop |
||
| 22 | # note expectation that no characters have already been escaped |
||
| 23 | for c in escape_chars: |
||
| 24 | ret_regex = ret_regex.replace(c, '\\' + c) |
||
| 25 | |||
| 26 | # remove any double alternations until these don't exist any more |
||
| 27 | while True: |
||
| 28 | old_regex = ret_regex |
||
| 29 | ret_regex = ret_regex.replace('||', '|') |
||
| 30 | if old_regex == ret_regex: |
||
| 31 | break |
||
| 32 | |||
| 33 | # if last char is alternation | remove it because this |
||
| 34 | # will cause operational error |
||
| 35 | # this can happen as user is typing in global search box |
||
| 36 | while len(ret_regex) >= 1 and ret_regex[-1] == '|': |
||
| 37 | ret_regex = ret_regex[:-1] |
||
| 38 | |||
| 39 | # and back to the caller |
||
| 40 | return ret_regex |
||
| 41 |