2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : non-portable (only on platforms that provide a regex lib)
12 -- Regular expression matching. Uses the POSIX regular expression
13 -- interface in "Text.Regex.Posix".
15 -----------------------------------------------------------------------------
18 -- * Regular expressions
20 #if !defined(__HUGS__) || defined(HAVE_REGEX_H)
29 import qualified Text.Regex.Posix as RE
30 import Text.Regex.Posix ( Regex )
31 import System.IO.Unsafe
33 #if !defined(__HUGS__) || defined(HAVE_REGEX_H)
34 -- | Makes a regular expression with the default options (multi-line,
35 -- case-sensitive). The syntax of regular expressions is
36 -- otherwise that of @egrep@ (i.e. POSIX \"extended\" regular
38 mkRegex :: String -> Regex
39 mkRegex s = unsafePerformIO (RE.regcomp s RE.regExtended)
41 -- | Makes a regular expression, where the multi-line and
42 -- case-sensitve options can be changed from the default settings.
44 :: String -- ^ The regular expression to compile
45 -> Bool -- ^ 'True' @\<=>@ @\'^\'@ and @\'$\'@ match the beginning and
46 -- end of individual lines respectively, and @\'.\'@ does /not/
47 -- match the newline character.
48 -> Bool -- ^ 'True' @\<=>@ matching is case-sensitive
49 -> Regex -- ^ Returns: the compiled regular expression
51 mkRegexWithOpts s single_line case_sensitive
52 = unsafePerformIO (RE.regcomp s (RE.regExtended + newline + igcase))
54 newline | single_line = RE.regNewline
57 igcase | case_sensitive = 0
58 | otherwise = RE.regIgnoreCase
60 -- | Match a regular expression against a string
62 :: Regex -- ^ The regular expression
63 -> String -- ^ The string to match against
64 -> Maybe [String] -- ^ Returns: @'Just' strs@ if the match succeeded
65 -- (and @strs@ is the list of subexpression matches),
66 -- or 'Nothing' otherwise.
68 case (unsafePerformIO (RE.regexec p str)) of
70 Just (before, match, after, sub_strs) -> Just sub_strs
72 -- | Match a regular expression against a string, returning more information
75 :: Regex -- ^ The regular expression
76 -> String -- ^ The string to match against
77 -> Maybe ( String, String, String, [String] )
78 -- ^ Returns: 'Nothing' if the match failed, or:
80 -- > Just ( everything before match,
82 -- > everything after the match,
83 -- > subexpression matches )
85 matchRegexAll p str = unsafePerformIO (RE.regexec p str)