Difference between revisions of "Regular expressions"

From CodeCodex

(Implementations)
(Erlang)
Line 4: Line 4:
  
 
==Implementations==
 
==Implementations==
 +
 +
===Erlang===
 +
 +
<pre>
 +
case re:run("cat dog mouse", "cat") of
 +
    {match, _} -> true;
 +
    nomatch    -> false
 +
end.
 +
</pre>
  
 
===Haskell===
 
===Haskell===
Line 80: Line 89:
 
http://www.regular-expressions.info/
 
http://www.regular-expressions.info/
  
 +
[[Category:Erlang]]
 
[[Category:Haskell]]
 
[[Category:Haskell]]
 
[[Category:Java]]
 
[[Category:Java]]
Line 88: Line 98:
 
[[Category:Python]]
 
[[Category:Python]]
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 +
[[Category:Tcl]]

Revision as of 16:51, 13 April 2011

Introduction

Regular Expressions are a way to search strings. There are implementations in various languages.

Implementations

Erlang

case re:run("cat dog mouse", "cat") of
    {match, _} -> true;
    nomatch    -> false
end.

Haskell

import Text.Regex
case matchRegex (mkRegex "cat") "cat dog mouse" of
  Just _  -> True
  Nothing -> False

Java

boolean found = "cat dog mouse".matches("cat"); // the entire string has to match (not just part of it)

import java.util.regex.*;

boolean found = Pattern.compile("cat").matcher("cat dog mouse").find(); // matches anywhere in the string

JavaScript

var pattern = /cat/;

var found = pattern.test("cat dog mouse");

OCaml

You need to first link with the Str library

#load "str.cma";; (* run this when in interactive mode *)
try
  ignore(Str.search_forward (Str.regexp "cat") "cat dog mouse" 0);
  true
with Not_found -> false

Perl

$found = "cat dog mouse" =~ /cat/;

PHP

$found = preg_match('/cat/', "cat dog mouse");

Python

Here is howto get a boolean result for a search.

import re

found = re.search('cat', 'cat dog mouse')

Ruby

Here is howto get a boolean result for a search.

found = !!(/cat/ =~ 'cat dog mouse')

Tcl

set found [regexp "cat" "cat dog mouse"]

Useful Links

http://www.regular-expressions.info/