Regular Expressions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ron

    #1

    Regular Expressions

    This is probably a repeated question, but try as I might I was unable
    to find something similar in the archives.

    I'm trying to develop a regular expression for recognizing a simplified
    C-Style string syntax. I need it to be able to handle escape sequences
    of the form \x where x is any character including ".

    Here's what I'm trying:

    \"([^"\\]|(\\.))*\"

    When I try to get it to recognize something like:

    "I said, \"Hello!\""

    It stops at the first quote after the \.

    I've used this very same regular expression in a parser generator I
    have for C++ and it works just fine.

    Any thoughts on what I'm doing wrong in the Python Reg Ex world?

    Thanks for the comments & help.

    Ron

  • MyHaz

    #2
    Re: Regular Expressions

    escape chars are always a pain when making regex's. There is a section
    on it the Regex HOWTO



    Comment

    • Roel Schroeven

      #3
      Re: Regular Expressions

      Ron wrote:[color=blue]
      > This is probably a repeated question, but try as I might I was unable
      > to find something similar in the archives.
      >
      > I'm trying to develop a regular expression for recognizing a simplified
      > C-Style string syntax. I need it to be able to handle escape sequences
      > of the form \x where x is any character including ".
      >
      > Here's what I'm trying:
      >
      > \"([^"\\]|(\\.))*\"
      >
      > When I try to get it to recognize something like:
      >
      > "I said, \"Hello!\""
      >
      > It stops at the first quote after the \.[/color]

      Works for me:
      [color=blue][color=green][color=darkred]
      >>> print re.search(r'\"([^"\\]|(\\.))*\"',[/color][/color][/color]
      .... r'"I said \"Hello!\""').g roup(0)
      "I said \"Hello!\""


      You can leave out the backslashes in fron of the first and last quotes
      in the regex, by the way, at least if you use ' instead of " to delimite it:
      [color=blue][color=green][color=darkred]
      >>> print re.search(r'"([^"\\]|(\\.))*"',[/color][/color][/color]
      .... r'"I said \"Hello!\""').g roup(0)
      "I said \"Hello!\""


      --
      If I have been able to see further, it was only because I stood
      on the shoulders of giants. -- Isaac Newton

      Roel Schroeven

      Comment

      Working...