07f155be200b8cd09d6602f5f804b4019acc0780
[ghc-base.git] / Text / Regex.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Text.Regex
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/core/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (only on platforms that provide a regex lib)
10 --
11 -- Regular expression matching.
12 -- Uses the POSIX regular expression interface in Text.Regex.Posix for now.
13 --
14 -----------------------------------------------------------------------------
15
16 module Text.Regex (
17     Regex,
18     mkRegex,
19     mkRegexWithOpts,
20     matchRegex,
21     matchRegexAll
22   ) where
23
24 import Prelude
25 import qualified Text.Regex.Posix as RE
26 import System.IO.Unsafe
27
28 type Regex = RE.Regex
29
30 mkRegex :: String -> Regex
31 mkRegex s = unsafePerformIO (RE.regcomp s RE.regExtended)
32
33 mkRegexWithOpts :: String -> Bool -> Bool -> Regex
34 mkRegexWithOpts s single_line case_sensitive
35    = unsafePerformIO (RE.regcomp s (RE.regExtended + newline + igcase))
36    where
37         newline | single_line = 0
38                 | otherwise   = RE.regNewline
39
40         igcase  | case_sensitive = 0 
41                 | otherwise      = RE.regIgnoreCase
42
43 matchRegex :: Regex -> String -> Maybe [String]
44 matchRegex p str = 
45   case (unsafePerformIO (RE.regexec p str)) of
46         Nothing -> Nothing
47         Just (before, match, after, sub_strs) -> Just sub_strs
48
49 matchRegexAll :: Regex -> String ->
50         Maybe ( String,  -- \$`
51                 String,  -- \$&
52                 String,  -- \$'
53                 [String] -- \$1..
54               )
55 matchRegexAll p str = unsafePerformIO (RE.regexec p str)
56