Search code examples
pythonpyparsing

PyParsing's searchString with StringStart() and StringEnd()


I'm trying to make the following tests pass:

from pyparsing import Word, nums, StringStart, StringEnd
import pytest

def get_square_feet(string):
    area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
    expression = StringStart() + area + "sqft" + StringEnd()
    return expression.parseString(string).get("area")

def test_get_square_feet():
    assert get_square_feet("800 sqft") == 800
    assert get_square_feet("9,000 sqft") == 9000

def test_get_square_feet_with_prefix():
    assert get_square_feet("size: 12,000 sqft") is None

if __name__ == "__main__":
    pytest.main([__file__])

However, the second tests fails because it leads to a ParseError. Instead, I'd like use searchString, but if I replace parseString by searchString in the get_square_feet function I also get an error because the function returns None. Can someone point out to me what is wrong here?


Solution

  • Here is the corresponding code using pyparsing, catching the ParseException:

    from pyparsing import Word, nums, StringStart, StringEnd, ParseException
    
    def get_square_feet(string):
        area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
        expression = StringStart() + area + "sqft" + StringEnd()
        try:
            return expression.parseString(string).get("area")
        except ParseException:
            return None