From d3e4f8547c098a143f4d37ae090ccc954384a7ea Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Thu, 16 Mar 2023 14:30:50 -1000 Subject: [PATCH] imp: lib: Hledger.Utils.String: more string strippers added: strip1Char stripBy strip1By Not used in hledger right now, but useful to offer in our scripting prelude. --- hledger-lib/Hledger/Utils/String.hs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/hledger-lib/Hledger/Utils/String.hs b/hledger-lib/Hledger/Utils/String.hs index 6edab75c2..14bb92ade 100644 --- a/hledger-lib/Hledger/Utils/String.hs +++ b/hledger-lib/Hledger/Utils/String.hs @@ -20,6 +20,9 @@ module Hledger.Utils.String ( strip, lstrip, rstrip, + strip1Char, + stripBy, + strip1By, chomp, chomp1, singleline, @@ -69,6 +72,25 @@ lstrip = dropWhile isSpace rstrip :: String -> String rstrip = reverse . lstrip . reverse +-- | Strip the given starting and ending character +-- from the start and end of a string if both are present. +strip1Char :: Char -> Char -> String -> String +strip1Char b e s = case s of + (c:cs) | c==b, not $ null cs, last cs==e -> init cs + _ -> s + +-- | Strip a run of zero or more characters matching the predicate +-- from the start and end of a string. +stripBy :: (Char -> Bool) -> String -> String +stripBy f = dropWhileEnd f . dropWhile f + +-- | Strip a single balanced enclosing pair of a character matching the predicate +-- from the start and end of a string. +strip1By :: (Char -> Bool) -> String -> String +strip1By f s = case s of + (c:cs) | f c, not $ null cs, last cs==c -> init cs + _ -> s + -- | Remove all trailing newlines/carriage returns. chomp :: String -> String chomp = reverse . dropWhile (`elem` "\r\n") . reverse