regex icon indicating copy to clipboard operation
regex copied to clipboard

Confused by Match type.

Open Magicloud opened this issue 6 years ago • 5 comments

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)?

Magicloud avatar Apr 10 '19 09:04 Magicloud

Never mind. Forgot they are in RegexBase.

Magicloud avatar Apr 10 '19 09:04 Magicloud

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 avatar Jul 31 '19 12:07 bergmark

@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)|]

cdornan avatar Jul 31 '19 13:07 cdornan

Thanks! i got it working now.

I think I expected the Replace module to only deal with replacement, so I never looked in there.

bergmark avatar Jul 31 '19 16:07 bergmark

Yes — I have had the sense that something was wring — this has helped bring it into focus 👍

cdornan avatar Jul 31 '19 19:07 cdornan