Difference between revisions of "Regular expressions"

From CodeCodex

(Implementations)
Line 69: Line 69:
 
<pre class="ruby">
 
<pre class="ruby">
 
found = !!(/cat/ =~ 'cat dog mouse')
 
found = !!(/cat/ =~ 'cat dog mouse')
 +
</pre>
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
set found [regexp "cat" "cat dog mouse"]
 
</pre>
 
</pre>
  

Revision as of 20:18, 21 February 2011

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

Tcl

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

Useful Links

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