Cookbook/Pattern matching

From HaskellWiki
< Cookbook
Revision as of 12:26, 22 October 2010 by Dino (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

Regular expressions are useful in some situations where the Data.List library is unwieldy. Posix style regular expressions are available in the core libraries, and a suite of other regular expression libraries are [also available], including PCRE and TRE-style regexes.

Bryan O'Sullivan has written a nice introduction to using the new regex libraries. This page describes the (=~) interface.

Text.Regex interface

Using the Text.Regex module, expressions can be applied with matchRegex and mkRegex with Maybe [String] results. Documentation for this module can be found on the Hackage regex-compat page.

$ ghci
Prelude> :m +Text.Regex

For boolean-style (either it succeeded or failed) results:

Prelude Text.Regex> matchRegex (mkRegex "a") "aabc"
Just []

Prelude Text.Regex> matchRegex (mkRegex "z") "aabc"
Nothing

With capturing results in the [String]:

Prelude Text.Regex> matchRegex (mkRegex "(a)") "aabc"
Just ["a"]

Prelude Text.Regex> matchRegex (mkRegex "(a+)") "aabc"
Just ["aa"]

Prelude Text.Regex> matchRegex (mkRegex "(a)(b)") "aabc"
Just ["a","b"]

Prelude Text.Regex> matchRegex (mkRegex "(z)") "aabc"
Nothing