Is there a way to use a number in pyparsing?

Viewed 43

I am using the python library PyParsing in python 3.8, and I am wondering if there is a way to parse numbers? Here is my current code:

from pyparsing import Word, alphas
getWordParse = Word(alphas)

alphas is only characters, would there be a way to use numbers as well?

1 Answers

Pyparsing provides several convenience constants for defining Word's:

alphas = "A-Z" + "a-z"
nums = "0-9"
alphanums = alphas + nums
alphas8bit = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ"
hexnums "0-9" + "A-F" + "a-f"
printables = any non-whitespace character

But these are all just strings, and you can define Words using string literals too:

word_of_even_digits = Word("02468", as_keyword=True)
word_of_even_digits.search_string("248 125 126 298 42 3.14159").as_list()

Prints:

[['248'], ['42']]

Pyparsing also includes some parsers for common expressions (like integer, real, fnumber, and number), which also include parse actions that will returned the parsed results as ints or floats, instead of just strs.

Here is a good "getting started" docs page: https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html

And here is the reference page on Word: https://pyparsing-docs.readthedocs.io/en/latest/pyparsing.html?highlight=Word#pyparsing.Word

Visit the pyparsing wiki for more info at: https://github.com/pyparsing/pyparsing/wiki

Related