Confused by Match type.
Apparently there is a matchArray contains all the captures. But I could not see it exposed anywhere. So how should I get the sub matches (by parens)?
Never mind. Forgot they are in RegexBase.
I got stuck on this as well, could someone give an example of how to extract captures?
I'm trying to do something like
_getMyTwoCaptures ("x,y" ?=~ [re|(.),(y)|]) == Just ("x", "y")
@bergmark sorry, this is not clear and it should be fixed so I am leaving it open.
The main problem is probably that you need to use Text.RE.Replace to work with captures.
Hopefully these examples will makes things a bit clearer. (Note the ${a}(...) construction for naming captures.)
{-# LANGUAGE QuasiQuotes #-}
import Text.RE.Replace
import Text.RE.TDFA.String
-- lists all of the captures (Nothing => no match)
caps1 :: String -> Maybe (Capture String,[Capture String])
caps1 s = matchCaptures $ s ?=~ [re|(.),(y)|]
-- lists all of the captured strings
caps2 :: String -> Maybe [String]
caps2 = fmap (map capturedText . snd) . caps1
-- using capture numbers, extracts capture '1' and '2' ('0' is whole regex)
caps3 :: String -> Maybe (String,String)
caps3 s = (,) <$> mtch !$$? [cp|1|] <*> mtch !$$? [cp|2|]
where
mtch = s ?=~ [re|(.),(y)|]
-- using named captures, extracts capture 'a' and 'b'
caps4 :: String -> Maybe (String,String)
caps4 s = (,) <$> mtch !$$? [cp|a|] <*> mtch !$$? [cp|b|]
where
mtch = s ?=~ [re|${a}(.),${b}(y)|]
-- if you want partial code that assumes matches then you can do this
caps5 :: String -> (String,String)
caps5 s = (mtch !$$ [cp|a|], mtch !$$ [cp|b|])
where
mtch = s ?=~ [re|${a}(.),${b}(y)|]
Thanks! i got it working now.
I think I expected the Replace module to only deal with replacement, so I never looked in there.
Yes — I have had the sense that something was wring — this has helped bring it into focus 👍