Regular expressions

From CodeCodex

Revision as of 05:51, 23 January 2011 by 211.2.129.92 (Talk)

Introduction

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

Implementations

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')

Useful Links

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