From de275540437c37d4f9ca905c74c58ee9a5dba925 Mon Sep 17 00:00:00 2001 From: Dion Moult Date: Thu, 7 Sep 2023 13:02:45 +1000 Subject: [PATCH] New substr formatting function. --- src/ifcopenshell-python/ifcopenshell/util/selector.py | 6 +++++- src/ifcopenshell-python/test/util/test_selector.py | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/ifcopenshell-python/ifcopenshell/util/selector.py b/src/ifcopenshell-python/ifcopenshell/util/selector.py index 46fcd6c9e8..ea41323999 100644 --- a/src/ifcopenshell-python/ifcopenshell/util/selector.py +++ b/src/ifcopenshell-python/ifcopenshell/util/selector.py @@ -115,7 +115,7 @@ get_element_grammar = lark.Lark( format_grammar = lark.Lark( """start: function - function: round | format_length | lower | upper | title | concat | ESCAPED_STRING | NUMBER + function: round | format_length | lower | upper | title | concat | substr | ESCAPED_STRING | NUMBER round: "round(" function "," NUMBER ")" format_length: metric_length | imperial_length @@ -125,6 +125,7 @@ format_grammar = lark.Lark( upper: "upper(" function ")" title: "title(" function ")" concat: "concat(" function ("," function)* ")" + substr: "substr(" function "," SIGNED_INT "," SIGNED_INT ")" // Embed common.lark for packaging DIGIT: "0".."9" @@ -181,6 +182,9 @@ class FormatTransformer(lark.Transformer): def concat(self, args): return "".join(args) + def substr(self, args): + return str(args[0])[int(args[1]):int(args[2])] + def round(self, args): return str(round(float(args[0]) / float(args[1])) * float(args[1])) diff --git a/src/ifcopenshell-python/test/util/test_selector.py b/src/ifcopenshell-python/test/util/test_selector.py index 4fd4972f75..d5306a84b3 100644 --- a/src/ifcopenshell-python/test/util/test_selector.py +++ b/src/ifcopenshell-python/test/util/test_selector.py @@ -34,6 +34,8 @@ class TestFormat(): assert subject.format('title(\"fOo\")') == "Foo" assert subject.format('concat(\"fOo\", \"bar\")') == "fOobar" assert subject.format('upper(concat(\"fOo\", \"bar\"))') == "FOOBAR" + assert subject.format('substr(\"foobar\", 1, 2)') == "o" + assert subject.format('substr(\"foobar\", 1, -1)') == "ooba" def test_number_formatting(self): assert subject.format("round(123, 5)") == "125.0"