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 Text.Regex.Posix ( Regex )
28 import System.IO.Unsafe
30 -- | Makes a regular expression with the default options (multi-line,
31 -- case-sensitive). The syntax of regular expressions is
32 -- otherwise that of @egrep@ (i.e. POSIX \"extended\" regular
34 mkRegex :: String -> Regex
35 mkRegex s = unsafePerformIO (RE.regcomp s RE.regExtended)
37 -- | Makes a regular expression, where the multi-line and
38 -- case-sensitve options can be changed from the default settings.
40 :: String -- ^ The regular expression to compile
41 -> Bool -- ^ 'True' @\<=>@ @\'^\'@ and @\'$\'@ match the beginning and
42 -- end of individual lines respectively, and @\'.\'@ does /not/
43 -- match the newline character.
44 -> Bool -- ^ 'True' @\<=>@ matching is case-sensitive
45 -> Regex -- ^ Returns: the compiled regular expression
47 mkRegexWithOpts s single_line case_sensitive
48 = unsafePerformIO (RE.regcomp s (RE.regExtended + newline + igcase))
50 newline | single_line = RE.regNewline
53 igcase | case_sensitive = 0
54 | otherwise = RE.regIgnoreCase
56 -- | Match a regular expression against a string
58 :: Regex -- ^ The regular expression
59 -> String -- ^ The string to match against
60 -> Maybe [String] -- ^ Returns: @'Just' strs@ if the match succeeded
61 -- (and @strs@ is the list of subexpression matches),
62 -- or 'Nothing' otherwise.
64 case (unsafePerformIO (RE.regexec p str)) of
66 Just (before, match, after, sub_strs) -> Just sub_strs
68 -- | Match a regular expression against a string, returning more information
71 :: Regex -- ^ The regular expression
72 -> String -- ^ The string to match against
73 -> Maybe ( String, String, String, [String] )
74 -- ^ Returns: 'Nothing' if the match failed, or:
76 -- > Just ( everything before match,
78 -- > everything after the match,
79 -- > subexpression matches )
81 matchRegexAll p str = unsafePerformIO (RE.regexec p str)