1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable (only on platforms that provide a regex lib)
11 -- Regular expression matching. Uses the POSIX regular expression
12 -- interface in "Text.Regex.Posix".
14 -----------------------------------------------------------------------------
17 -- * Regular expressions
26 import qualified Text.Regex.Posix as RE
27 import System.IO.Unsafe
29 -- | A compiled regular expression
32 -- | Makes a regular expression with the default options (multi-line,
33 -- case-sensitive). The syntax of regular expressions is
34 -- otherwise that of @egrep@ (i.e. POSIX \"extended\" regular
36 mkRegex :: String -> Regex
37 mkRegex s = unsafePerformIO (RE.regcomp s RE.regExtended)
39 -- | Makes a regular expression, where the multi-line and
40 -- case-sensitve options can be changed from the default settings.
42 :: String -- ^ The regular expression to compile
43 -> Bool -- ^ 'True' @\<=>@ '@^@' and '@$@' match the beginning and
44 -- end of individual lines respectively, and '.' does /not/
45 -- match the newline character.
46 -> Bool -- ^ 'True' @\<=>@ matching is case-sensitive
47 -> Regex -- ^ Returns: the compiled regular expression
49 mkRegexWithOpts s single_line case_sensitive
50 = unsafePerformIO (RE.regcomp s (RE.regExtended + newline + igcase))
52 newline | single_line = 0
53 | otherwise = RE.regNewline
55 igcase | case_sensitive = 0
56 | otherwise = RE.regIgnoreCase
58 -- | Match a regular expression against a string
60 :: Regex -- ^ The regular expression
61 -> String -- ^ The string to match against
62 -> Maybe [String] -- ^ Returns: @'Just' strs@ if the match succeeded
63 -- (and @strs@ is the list of subexpression matches),
64 -- or 'Nothing' otherwise.
66 case (unsafePerformIO (RE.regexec p str)) of
68 Just (before, match, after, sub_strs) -> Just sub_strs
70 -- | Match a regular expression against a string, returning more information
73 :: Regex -- ^ The regular expression
74 -> String -- ^ The string to match against
75 -> Maybe ( String, String, String, [String] )
76 -- ^ Returns: 'Nothing' if the match failed, or:
78 -- > Just ( everything before match,
80 -- > everything after the match,
81 -- > subexpression matches )
83 matchRegexAll p str = unsafePerformIO (RE.regexec p str)