1 | def clean_regex(regex): |
||
0 ignored issues
–
show
|
|||
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: |
||
0 ignored issues
–
show
The name
c does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ ).
This check looks for invalid names for a range of different identifiers. You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements. If your project includes a Pylint configuration file, the settings contained in that file take precedence. To find out more about Pylint, please refer to their site.
Loading history...
|
|||
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 |
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.