From 4890d2bf908df32bf69ea729c2b1a28e47072cc5 Mon Sep 17 00:00:00 2001 From: Bryan Richter Date: Mon, 30 Jan 2017 09:17:18 -0800 Subject: [PATCH] Escape account names (#499) Fixes #498. --- hledger-lib/Hledger/Data/AccountName.hs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/hledger-lib/Hledger/Data/AccountName.hs b/hledger-lib/Hledger/Data/AccountName.hs index d70fb50f5..c11fa0c6c 100644 --- a/hledger-lib/Hledger/Data/AccountName.hs +++ b/hledger-lib/Hledger/Data/AccountName.hs @@ -149,15 +149,22 @@ clipOrEllipsifyAccountName :: Int -> AccountName -> AccountName clipOrEllipsifyAccountName 0 = const "..." clipOrEllipsifyAccountName n = accountNameFromComponents . take n . accountNameComponents +-- | Escape an AccountName for use within a regular expression. +-- >>> putStr $ escapeName "First?!#$*?$(*) !@^#*? %)*!@#" +-- First\?!#\$\*\?\$\(\*\) !@\^#\*\? %\)\*!@# +escapeName :: AccountName -> Regexp +escapeName = regexReplaceBy "[[?+|()*\\\\^$]" ("\\" <>) + . T.unpack + -- | Convert an account name to a regular expression matching it and its subaccounts. accountNameToAccountRegex :: AccountName -> Regexp accountNameToAccountRegex "" = "" -accountNameToAccountRegex a = printf "^%s(:|$)" (T.unpack a) +accountNameToAccountRegex a = printf "^%s(:|$)" (escapeName a) -- | Convert an account name to a regular expression matching it but not its subaccounts. accountNameToAccountOnlyRegex :: AccountName -> Regexp accountNameToAccountOnlyRegex "" = "" -accountNameToAccountOnlyRegex a = printf "^%s$" $ T.unpack a -- XXX pack +accountNameToAccountOnlyRegex a = printf "^%s$" $ escapeName a -- XXX pack -- | Convert an exact account-matching regular expression to a plain account name. accountRegexToAccountName :: Regexp -> AccountName