Regular expressions

From CodeCodex

Revision as of 09:43, 11 June 2010 by 169.232.246.15 (Talk)

Introduction

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

Implementations

Haskell

<HIGHLIGHTSYNTAX language = "haskell"> import Text.Regex case matchRegex (mkRegex "cat") "cat dog mouse" of

 Just _  -> True
 Nothing -> False

</HIGHLIGHTSYNTAX>

Java

<HIGHLIGHTSYNTAX language = "java122"> 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 </HIGHLIGHTSYNTAX>

JavaScript

<HIGHLIGHTSYNTAX language = "javascript"> var pattern = /cat/;

var found = pattern.test("cat dog mouse"); </HIGHLIGHTSYNTAX>

OCaml

You need to first link with the Str library <HIGHLIGHTSYNTAX language = "ocaml">

  1. 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 </HIGHLIGHTSYNTAX>

Perl

<HIGHLIGHTSYNTAX language = "perl"> $found = "cat dog mouse" =~ /cat/; </HIGHLIGHTSYNTAX>

PHP

<HIGHLIGHTSYNTAX language = "php3"> $found = preg_match('/cat/', "cat dog mouse"); </HIGHLIGHTSYNTAX>

Python

Here is howto get a boolean result for a search. <HIGHLIGHTSYNTAX language = "python"> import re

found = re.search('cat', 'cat dog mouse') </HIGHLIGHTSYNTAX>

Ruby

Here is howto get a boolean result for a search. <HIGHLIGHTSYNTAX language = "ruby"> found = ('cat dog mouse' =~ /cat/) != nil </HIGHLIGHTSYNTAX>

Useful Links

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