Regular Expression Literal

Summary

Creates a regular expression value.

Syntax

/pattern/[g][m][i]

Parameters

pattern
A valid ECMAScript 3 regular expression pattern.
g
Global match. Match the regular expression pattern globally and return all matches.
m
Multiline match. Match the ^ and $ anchors across multiple lines.
i
Ignore case. Performs a case-insensitive match.

Description

Regular expression literals create a regular expression value.

Regular expression literals can be used as a shorthand for instantiating System.RegExp. Thus, the following statements are equivalent:

1
2
System.RegExp re = /foo*bar/;
System.RegExp re = new System.RegExp(/foo*bar/);

An "empty" regular expression can be created by specifying a pattern with only an empty non-capturing group:

1
System.RegExp empty = /(?:)/;

Flags

Regular expression literals allow three different flags: global match ("g"), multiline match ("m"), and case-insensitive match ("i").

Global Match

A global match will return all matches instead of just the first match. For example:

1
2
"aaa".match(/a/);  // [ "a" ]
"aaa".match(/a/g); // [ "a", "a", "a" ]

Multiline Match

A multi-line match will return matches the start (^) and end ($) anchors across multiple lines. For example:

1
2
3
4
5
6
7
8
string aaa =
    """a
    a
    a""";
 
aaa.match(/^a/g);  // [ "a" ]
aaa.match(/^a/m);  // [ "a" ]
aaa.match(/^a/gm); // [ "a", "a", "a" ]

Notice how the "g" and "m" flags by themselves do not match across all lines. In combination, all matches across all lines will be returned.

Case-insensitive Match

A case-insensitive match will match all ignore whether a character is uppercase or lowercase. For example:

1
2
"A".match(/a/);  // false
"A".match(/a/i); // true

See Also

Share

HTML | BBCode | Direct Link