Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean Python Regular Expressions

Tags:

python

regex

list

Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.

patterns = [
    re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
    re.compile(r'\n+|\s{2}')
]
like image 586
KeyboardInterrupt Avatar asked Jun 06 '09 02:06

KeyboardInterrupt


People also ask

How do you clear a regular expression in Python?

Remove multiple characters from string using regex in python For that we need to pass such a pattern in the sub() function, that matches all the occurrences of character 's', 'a' & 'i' in the given string. Then sub() function should replace all those characters by an empty string i.e.

How do I get rid of the symbol in Python?

Short answer: Use string. replace() .

Is there regex in Python?

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.


3 Answers

You can use verbose mode to write more readable regular expressions. In this mode:

  • Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash.
  • When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.

The following two statements are equivalent:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")

(Taken from the documentation of verbose mode)

like image 170
Ayman Hourieh Avatar answered Oct 02 '22 19:10

Ayman Hourieh


Though @Ayman's suggestion about re.VERBOSE is a better idea, if all you want is what you're showing, just do:

patterns = re.compile(
        r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'
        r'\n+|\s{2}'
)

and Python's automatic concatenation of adjacent string literals (much like C's, btw) will do the rest;-).

like image 13
Alex Martelli Avatar answered Oct 02 '22 19:10

Alex Martelli


You can use comments in regex's, which make them much more readable. Taking an example from http://gnosis.cx/publish/programming/regular_expressions.html :

/               # identify URLs within a text file
          [^="] # do not match URLs in IMG tags like:
                # <img src="http://mysite.com/mypic.png">
http|ftp|gopher # make sure we find a resource type
          :\/\/ # ...needs to be followed by colon-slash-slash
      [^ \n\r]+ # stuff other than space, newline, tab is in URL
    (?=[\s\.,]) # assert: followed by whitespace/period/comma 
/
like image 2
Nathaniel Flath Avatar answered Oct 02 '22 18:10

Nathaniel Flath