Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing pyparsing to parse a list from a string with special characters
    primarykey
    data
    text
    <p>I'd like to parse a list from a string field that may contain special characters such as \ \n \r \n \t and expand over multiple lines. Currently, I have to parse the string first, clean it up, then apply the list grammar on the that clean string. It works ok but just wondering if there's a better way.</p> <p>This is what I current have</p> <pre><code>str_ = QuotedString('"',escChar='\\',multiline=True) #grammar for str str_.setParseAction(lambda pr: pr[0].replace('\\n',' ')\ .replace('\\r', ' ')\ .replace('\r', ' ')\ .replace('\t', ' ')) list_G = delimitedList(Word(printables))('mlist') #grammar for list def pa(st,locn,pr): return list_G.parseString(pr.mystr) mylist = Group(str_('mystr').addParseAction(pa)) #read in the str then re-parse G = Keyword("LIST") + mylist('thelist') + ';' #grammar for the whole thing s = 'LIST "one,two,three" ;' </code></pre> <p>Edit: Instead of Word(printables) in list_G, changed to </p> <pre><code>var_grammar = Word(alphas+"_", alphanums + "_") #"_a,a2b_,.." num_grammar = Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")('num') list_G = delimitedList(var_grammar|num_grammar)('mlist') #grammar for list G = Keyword("LIST") + '"' + mylist('thelist') + '"' + ';' </code></pre> <p>The reason that forces me to do the clean up above that replaces <code>"\\n", "\\r" with ' '</code> is because I read in string from a file that literally contains the the charactors <code>\n, \r</code> and those are not parsable by var_name or num (they are not printable)</p> <p>This is an example of a (raw) string in the file :</p> <pre><code>LIST "one,two, three, \nfour,\rfive"; </code></pre> <p>Do you have any suggestion about this ?</p>
    singulars
    1. This table or related slice is empty.
    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