Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrectly parsing string literals with python's re module
    primarykey
    data
    text
    <p>I'm trying to add some light markdown support for a javascript preprocessor which I'm writing in Python.</p> <p>For the most part it's working, but sometimes the regex I'm using is acting a little odd, and I think it's got something to do with raw-strings and escape sequences. </p> <p>The regex is: <code>(?&lt;!\\)\"[^\"]+\"</code></p> <p>Yes, I am aware that it only matches strings beginning with a <code>"</code> character. However, this project is born out of curiosity more than anything, so I can live with it for now. </p> <p>To break it down:</p> <pre><code>(?&lt;\\)\" # The group should begin with a quotation mark that is not escaped [^\"]+ # and match any number of at least one character that is not a quotation mark (this is the biggest problem, I know) \" # and end at the first quotation mark it finds </code></pre> <p>That being said, I (obviously) start hitting problems with things like this:</p> <p><code>"This is a string with an \"escaped quote\" inside it"</code></p> <p>I'm not really sure how to say "Everything but a quotation mark, unless that mark is escaped". I tried:</p> <pre><code>([^\"]|\\\")+ # a group of anything but a quote or an escaped quote </code></pre> <p>, but that lead to very strange results.</p> <p>I'm fully prepared to hear that I'm going about this all wrong. For the sake of simplicity, let's say that this regex will always start and end with double quotes (<code>"</code>) to avoid adding another element in the mix. I really want to understand what I have so far. </p> <p>Thanks for any assistance.</p> <p><strong>EDIT</strong></p> <p>As a test for the regex, I'm trying to find all string literals in the minified jQuery script with the following code (using the unutbu's pattern below):</p> <pre><code>STRLIT = r'''(?x) # verbose mode (?&lt;!\\) # not preceded by a backslash " # a literal double-quote .*? # non-greedy 1-or-more characters (?&lt;!\\) # not preceded by a backslash " # a literal double-quote ''' f = open("jquery.min.js","r") jq = f.read() f.close() literals = re.findall(STRLIT,jq) </code></pre> <p>The answer below fixes almost all issues. The ones that do arise are within jquery's own regular expressions, which is a very edge case. The solution no longer misidentifies valid javascript as markdown links, which was really the goal. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload