News for hackers. Stuff that matters.
Re:Python best practices by bayareaguy on Tuesday July 08, 2008 @10:25PM (#240680)
Most of that stuff is a bit silly but I learned python before it supported verbose regular expressions so I found this example useful.

  finder = re.compile(r"""
    ^ \s*         # start at beginning+ opt spaces
    ( [\[\]] )    # Group 1: opening bracket
    \s*           # optional spaces
    ( [-+]? \d+ ) # Group 2: first number
    \s* , \s*     # opt spaces+ comma+ opt spaces
    ( [-+]? \d+ ) # Group 3: second number
    \s*           # opt spaces
    ( [\[\]] )    # Group 4: closing bracket
    \s* $         # opt spaces+ end at the end
    """, flags=re.VERBOSE)
Re:Python best practices by ken on Wednesday July 09, 2008 @01:06PM (#241373)
I love regular expressions as much as anybody, but I never understood why people wrote code like that.

r"\s" is repeated 6 times in there, each time with a comment. Is there a reason nobody uses DRY when writing a regexp?

    spaces = r"\s*"
    number = r"([-+]?\d+)"
    bracket = r"([\[\]])"
    finder = re.compile(spaces.join(["^", bracket, number, ",", number, bracket, "$"]))
Re:Python best practices by delackner on Thursday July 10, 2008 @02:52AM (#242127)
That is the most beautiful bit of RE I have seen in ages. Thank you.

I always do one-off RE transformations of text in vi or even just sed, but this alone is reason enough to start writing my more complicated RE one-offs in Python.