-1

I need to handle backslash and tilde while using pyparsing in my piece of code and to keep it simple I used printables but this code raises an exception:

    import string
    import pyparsing as pp
    from pyparsing import *

    log_display = ("[pts\0]")
    log_display1 = ("[~~  ]")

    ut_user = "[" + Word(printables) + "]"

    log = ut_user

    data = log.parseString(log_display)
    print(data.dump())

Thanks for any help!

nlp
  • 109
  • 1
  • 4
  • 19
  • 2
    pyparsing does not do implicit backtracking like regular expressions do, so `Word(printables)` will also consume the trailing ']'. You'll get some better diagnostics if you use `data.runTests([log_display, log_display1])`. You'll also have to fix the \0 null as reported by user2357112 - just prefix your string with an 'r', as shown in his answer. – PaulMcG Nov 17 '18 at 03:20
  • thanks PaulMcG for being so helpful as always! – nlp Nov 17 '18 at 19:27

1 Answers1

1

"[pts\0]" does not have a backslash in it. It has a null character. If you wanted a string with a backslash, r"[pts\0]" would produce one. When reading input, this will generally not be a problem. String literal escape processing is only applied to string literals, not to user input.

The problem with "[~~ ]" has nothing to do with the tilde. The tilde is fine. The problem is the space, which doesn't count as a printable by the standards of pyparsing.printables. pyparsing.printables is a string containing all ASCII, printable, non-whitespace characters. The proper way to deal with this depends on what characters you actually want to allow.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Oh Cool thanks. How can I handle the null character? Do I leave out the values after the string or split it? I need only the "pts" if it makes sense. – nlp Nov 16 '18 at 19:57