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 : portable
11 -- Regular expression matching. Uses the POSIX regular expression
12 -- interface in "Text.Regex.Posix".
14 -----------------------------------------------------------------------------
16 -- * Regular expressions
25 import qualified Text.Regex.Posix as RE
26 import Text.Regex.Posix ( Regex )
27 import System.IO.Unsafe
29 -- | Makes a regular expression with the default options (multi-line,
30 -- case-sensitive). The syntax of regular expressions is
31 -- otherwise that of @egrep@ (i.e. POSIX \"extended\" regular
33 mkRegex :: String -> Regex
34 mkRegex s = unsafePerformIO (RE.regcomp s RE.regExtended)
36 -- | Makes a regular expression, where the multi-line and
37 -- case-sensitive options can be changed from the default settings.
39 :: String -- ^ The regular expression to compile
40 -> Bool -- ^ 'True' @\<=>@ @\'^\'@ and @\'$\'@ match the beginning and
41 -- end of individual lines respectively, and @\'.\'@ does /not/
42 -- match the newline character.
43 -> Bool -- ^ 'True' @\<=>@ matching is case-sensitive
44 -> Regex -- ^ Returns: the compiled regular expression
46 mkRegexWithOpts s single_line case_sensitive
47 = unsafePerformIO (RE.regcomp s (RE.regExtended + newline + igcase))
49 newline | single_line = RE.regNewline
52 igcase | case_sensitive = 0
53 | otherwise = RE.regIgnoreCase
55 -- | Match a regular expression against a string
57 :: Regex -- ^ The regular expression
58 -> String -- ^ The string to match against
59 -> Maybe [String] -- ^ Returns: @'Just' strs@ if the match succeeded
60 -- (and @strs@ is the list of subexpression matches),
61 -- or 'Nothing' otherwise.
63 case (unsafePerformIO (RE.regexec p str)) of
65 Just (before, match, after, sub_strs) -> Just sub_strs
67 -- | Match a regular expression against a string, returning more information
70 :: Regex -- ^ The regular expression
71 -> String -- ^ The string to match against
72 -> Maybe ( String, String, String, [String] )
73 -- ^ Returns: 'Nothing' if the match failed, or:
75 -- > Just ( everything before match,
77 -- > everything after the match,
78 -- > subexpression matches )
80 matchRegexAll p str = unsafePerformIO (RE.regexec p str)