Подтвердить что ты не робот

Замена/подстановка с помощью регулярных выражений Haskell

Существует ли API высокого уровня для выполнения поиска и замены с помощью регулярных выражений в Haskell? В частности, я смотрю пакеты Text.Regex.TDFA или Text.Regex.Posix. Мне бы очень хотелось что-то типа:

f :: Regex -> (ResultInfo -> m String) -> String -> m String

так, например, чтобы заменить "собаку" на "кошку", вы могли бы написать

runIdentity . f "dog" (return . const "cat")    -- :: String -> String

или делать более продвинутые вещи с монадой, например, подсчеты и т.д.

Документация Haskell для этого довольно не хватает. Некоторые низкоуровневые примечания API здесь.

4b9b3361

Ответ 1

Как насчет subRegex в пакете Text.Regex?

Prelude Text.Regex> :t subRegex
subRegex :: Regex -> String -> String -> String

Prelude Text.Regex> subRegex (mkRegex "foo") "foobar" "123"
"123bar"

Ответ 2

Я не знаю какой-либо существующей функции, которая создает эту функциональность, но я думаю, что я бы использовал что-то вроде AllMatches [] (MatchOffset, MatchLength) RegexContent, чтобы имитировать его:

replaceAll :: RegexLike r String => r -> (String -> String) -> String -> String
replaceAll re f s = start end
  where (_, end, start) = foldl' go (0, s, id) $ getAllMatches $ match re s
        go (ind,read,write) (off,len) =
          let (skip, start) = splitAt (off - ind) read 
              (matched, remaining) = splitAt len matched 
          in (off + len, remaining, write . (skip++) . (f matched ++))

replaceAllM :: (Monad m, RegexLike r String) => r -> (String -> m String) -> String -> m String
replaceAllM re f s = do
  let go (ind,read,write) (off,len) = do
      let (skip, start) = splitAt (off - ind) read 
      let (matched, remaining) = splitAt len matched 
      replacement <- f matched
      return (off + len, remaining, write . (skip++) . (replacement++))
  (_, end, start) <- foldM go (0, s, return) $ getAllMatches $ match re s
  start end

Ответ 3

Основываясь на ответе @rampion, но с зафиксированной опечаткой, это не просто <<loop>>:

replaceAll :: Regex -> (String -> String) -> String -> String
replaceAll re f s = start end
  where (_, end, start) = foldl' go (0, s, id) $ getAllMatches $ match re s
        go (ind,read,write) (off,len) =
            let (skip, start) = splitAt (off - ind) read 
                (matched, remaining) = splitAt len start 
            in (off + len, remaining, write . (skip++) . (f matched ++))

Ответ 4

Возможно, этот подход подходит вам.

import Data.Array (elems)
import Text.Regex.TDFA ((=~), MatchArray)

replaceAll :: String -> String -> String -> String        
replaceAll regex new_str str  = 
    let parts = concat $ map elems $ (str  =~  regex :: [MatchArray])
    in foldl (replace' new_str) str (reverse parts) 

  where
     replace' :: [a] -> [a] -> (Int, Int) -> [a]
     replace' new list (shift, l)   = 
        let (pre, post) = splitAt shift list
        in pre ++ new ++ (drop l post)

Ответ 5

Вы можете использовать replaceAll из Data.Text.ICU.Replace module.

Prelude> :set -XOverloadedStrings
Prelude> import Data.Text.ICU.Replace
Prelude Data.Text.ICU.Replace> replaceAll "cat" "dog" "Bailey is a cat, and Max is a cat too."
"Bailey is a dog, and Max is a dog too."