MooTools - Regular Expression

MooTools provides a way to create and use Regular Expression (regex). This tutorial will explain the basics and extreme uses of regexes.

Let us discuss a few methods of the regular expressions.

test()

test() is a method used to test the regular expression with the input string. While JavaScript already provides the RegExp object along with the test() function, MooTools adds more features to the RegExp object. Let us take an example and understand how to use the test() method. Take a look at the following code.

Output

Ignore Case

This is one of the important situations in regular expressions concept. If you don’t want a regular expression to be case sensitive, you call the test method with an option 'I'. Let us take an example that will explain the ignore case in regular expression. Take a look at the following code.

Output

Regex starts with '^'

The regex '^' (cap) is a special operator that allows you to check the regular expression in the beginning of a given string. This operator is used as prefix to the regular expression. Let us take an example that will explain how to use this operator. Take a look at the following code.

Output

Regex ends with '$'

The Regex '$' (dollar) is a special operator that allows you to check the regular expression at the end of a given string. This operator is used as suffix to the regular expression. Let us take an example that will explain how to use this operator. Take a look at the following code.

Output

Character Classes

Character classes are a phase of regular expressions that allow you to match specific characters (A or Z) or range of characters (A — Z). For example, you want to test if either of the words foo and zoo exist in a string, classes allow you to do this by placing the characters in the box brackets [] with the regular expressions. Take a look at the following code.

Output

escapeRegExp()

This method is used to ignore the escape characters from a given string while checking it with a regular expression. Usually, the escape characters are −

- . * + ? ^ $ { } ( ) | [ ] / \

Let us take an example wherein, we have a given String like "[check-this-stuff] it is $900". If you want to take this whole string you have to declare it like this — "\[check\-this\-stuff\] it is \$900". The system accepts only this pattern. We do not use the escakpe character patterns in MooTools. We have the escapeRegExp() method to ignore escape characters. Take a look at the following code.