Haskellの正規表現によるマッチ判定・文字列の置換・文字列の分割

  • Text.Regex.Posix の (=~) 関数を使った置換
import Text.Regex.Posix

replace str old new | match == "" = str
                    | otherwise   = headStr ++ new ++ replace tailStr old new
    where
        (headStr,match,tailStr) =  str =~ old ::(String,String,String)
import Text.Regex.Posix

replace str old new = 
  let (a,b,c) = str =~ old ::(String,String,String) 
  in if b=="" then str else a ++ new ++ replace c old new
 *Main> replace "Hello,1234!" "[0123456789]+" "world"
 "Hello,world!"

 *Main> replace "Hello,1234!" "abcd" "world"
 "Hello,1234!"

 *Main> replace "Hello,1234! Hello,1234!" "[0123456789]+" "world"
 "Hello,world! Hello,world!"

20140321 追記

           -- subRegex :: Regex -> String -> String -> String
Text.Regex > subRegex (mkRegex "([a-z]+) ([A-Z]+)") "abc DEF" "[\\1]-----[\\2]"
 -- > "[abc]-----[DEF]"
Text.Regex> matchRegex (mkRegex "xxx") "abc DEF abc"
 -- > Nothing
Text.Regex> matchRegex (mkRegex "abc") "abc DEF abc"
 -- > Just []
Text.Regex> matchRegex (mkRegex "(abc)") "abc DEF abc"
-- > Just ["abc"]
Text.Regex> matchRegexAll (mkRegex "[A-Z]+") "abc DEF abc abc"
--> Just ("abc ","DEF"," abc abc",[])

Text.Regex> matchRegexAll (mkRegex "([A-Z]+)") "abc DEF abc DEF abc"
-- > Just ("abc ","DEF"," abc DEF abc",["DEF"])
  • matchRegexAll
Text.Regex> matchRegexAll (mkRegex "(abc) ([A-Z]+) (hello)") "head abc DEF hello tail"
Just ("head ","abc DEF hello"," tail",["abc","DEF","hello"])
Text.Regex> splitRegex (mkRegex "[A-Z]+") "headABCtailXYZxyz"
-- > ["head","tail","xyz"]

mkRegexWithOpts は引数の指定でマッチする条件が変わる。第2、第3引数をTreu にすると mkRegexと同じ動作になります。

-- 3番目の引数がTrueのときは大文字、小文字を区別する
>  matchRegex (mkRegexWithOpts "ABC" True True) "_abc DEF abc"
-- > Nothing
-- 3番目の引数がFalseのときは大文字、小文字を区別しない
>  matchRegex (mkRegexWithOpts "ABC" True False) "_abc DEF abc"
-- > Just []

-- 2番目の引数がTrueのとき、'^'、'$' の判定に改行を意識する。
>  matchRegex (mkRegexWithOpts "^abc$" True True) "\nabc\n DEF abc"
-- > Just []
-- 2番目の引数がFalseのとき、'^'、'$' の判定に改行を意識する。
>  matchRegex (mkRegexWithOpts "^abc$" False True) "\nabc\n DEF abc"
-- > Nothing

-- 2番目の引数がTrueのとき、'.'は改行にマッチしない。
>  matchRegex (mkRegexWithOpts "^.abc" True True) "\nabc"
-- > Nothing
-- 2番目の引数がFalseのとき、'.'は改行にマッチする。
>  matchRegex (mkRegexWithOpts "^.abc" False True) "\nabc"
-- > Just []