Regular expressions

From CodeCodex

Introduction[edit]

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

Implementations[edit]

Erlang[edit]

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

Haskell[edit]

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

Java[edit]

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[edit]

var pattern = /cat/;

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

OCaml[edit]

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[edit]

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

PHP[edit]

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

Python[edit]

Here is howto get a boolean result for a search.

import re

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

Ruby[edit]

Here is howto get a boolean result for a search.

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

Another way

found = /cat/ === 'cat dog mouse'

Tcl[edit]

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

Useful Links[edit]

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