Search code examples
haskellparsec

Find substring in a string with parsec


For example, I want to get "abc" from "aabbccabc", which should be easy with regex. But i want to use parsec. It seems that try can do that, but that must be quite inefficient...

I tried:

import Text.ParserCombinators.Parsec
ps pser txt = case (parse pser  "" txt ) of
  Left e  -> show e
  Right v -> v

and got the following result:

λ> ps (string "asf") "  dsfdsasf"
"(line 1, column 1):\nunexpected \" \"\nexpecting \"asf\""

Solution

  • You can do something like this:

    {-# LANGUAGE FlexibleContexts #-}
    
    import Text.Parsec
    import Text.Parsec.Char
    
    findSubString str = try (string str) <|> (anyChar *> findSubString str)
    
    foo = do
      findSubString "abc"
      findSubString "def"
    
    test1 = parseTest foo "this is abc"         -- fails: expecting def
    
    test2 = parseTest foo "this is abc and de"  -- fails: expecting def
    
    test3 = parseTest foo "this is abc and def" -- succeeds