Core JavaScript 1.5 Reference:Global Objects:RegExp
From MDC
Contents |
Summary
Creates a regular expression object for matching text according to a pattern.
Syntax
var regex = new RegExp("pattern" [, "flags"]);
var literal = /pattern/flags;
Parameters
-
pattern - The text of the regular expression.
-
flags - If specified, flags can have any combination of the following values:
-
g - global match
-
i - ignore case
-
m - match over multiple lines
-
y - New in Firefox 3
- sticky; matches only from the index indicated by the
lastIndexproperty of this regular expression in the target string (and does not attempt to match from any later indexes). This allows the match-only-at-start capabilities of the character "^" to effectively be used at any location in a string by changing the value of thelastIndexproperty.
-
Description
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = new RegExp("\\w+");
var re = /\w+/;
Notice that the parameters to the literal format do not use quotation marks to indicate strings, while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:
/ab+c/i;
new RegExp("ab+c", "i");
Special characters in regular expressions
| Character | Meaning |
\ |
For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally. For example, or For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally. For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, |
^ |
Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, |
$ |
Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, |
* |
Matches the preceding item 0 or more times. For example, |
+ |
Matches the preceding item 1 or more times. Equivalent to For example, |
? |
Matches the preceding item 0 or 1 time. For example, If used immediately after any of the quantifiers Also used in lookahead assertions, described under |
. |
(The decimal point) matches any single character except the newline characters: \n \r \u2028 or \u2029. ( For example, |
(x) |
Matches For example, |
(?:x) |
Matches |
x(?=y) |
Matches |
x(?!y) |
Matches
|
x|y |
Matches either For example, |
{n} |
Where For example, |
{n,} |
Where For example, |
{n,m} |
Where For example, |
[xyz] |
A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen. For example, |
[^xyz] |
A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen. For example, |
[\b] |
Matches a backspace. (Not to be confused with |
\b |
Matches a word boundary, such as a space. (Not to be confused with For example, |
\B |
Matches a non-word boundary. For example, |
\cX |
Where For example, |
\d |
Matches a digit character in the basic Latin alphabet. Equivalent to Note: In Firefox 2 and earlier, matches a digit character from any alphabet. (bug 378738) For example, |
\D |
Matches any non-digit character in the basic Latin alphabet. Equivalent to Note: In Firefox 2 and earlier, all alphabet. (bug 378738) For example, |
\f |
Matches a form-feed. |
\n |
Matches a linefeed. |
\r |
Matches a carriage return. |
\s |
Matches a single white space character, including space, tab, form feed, line feed and other unicode spaces.[1] For example, |
\S |
Matches a single character other than white space.[2] For example, |
\t |
Matches a tab. |
\v |
Matches a vertical tab. |
\w |
Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to For example, |
\W |
Matches any character that is not a word character from the basic Latin alphabet. Equivalent to For example, |
\n |
Where For example, |
\0 |
Matches a NUL character. Do not follow this with another digit. |
\xhh |
Matches the character with the code |
\uhhhh |
Matches the character with the Unicode value |
The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
- ^ Equivalent to:
[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
- ^ Equivalent to:
[^\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
Properties
For properties inherited by RegExp instances, see Properties of RegExp instances.
- prototype
- Allows the addition of properties to all objects.
Properties inherited from Function.prototype
caller, constructor, length, name
Methods
For methods inherited by RegExp instances, see Methods of RegExp instances.
The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.
Methods inherited from Object.prototype
__defineGetter__, __defineSetter__, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, unwatch, watch
RegExp instances
RegExp instances inherit from RegExp.prototype. Modifications to the prototype object are propagated to all RegExp instances.
Properties
Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.
- constructor
- Specifies the function that creates an object's prototype.
- global
- Whether to test the regular expression against all possible matches in a string, or only against the first.
- ignoreCase
- Whether to ignore case while attempting a match in a string.
- lastIndex
- The index at which to start the next match.
- multiline
- Whether or not to search in strings across multiple lines.
- source
- The text of the pattern.
Methods
- exec
- Executes a search for a match in its string parameter.
- test
- Tests for a match in its string parameter.
- toSource
- Non-standard
- Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource method.
- toString
- Returns a string representing the specified object. Overrides the Object.prototype.toString method.
Methods inherited from Object.prototype
__defineGetter__, __defineSetter__, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, unwatch, valueOf, watch
Examples
Example: Using a regular expression to change data format
The following script uses the replace method inherited by the String instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.
var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); print(newstr);
This displays "Smith, John".
Example: Using a regular expression with the "sticky" flag
This example demonstrates how one could use the sticky flag on regular expressions to match individual lines of multiline input.
var text = "First line\nsecond line"; var regex = /(\S+) line\n?/y; var match = regex.exec(text); print(match[1]); // prints "First" print(regex.lastIndex); // prints 11 var match2 = regex.exec(text); print(match2[1]); // prints "Second" print(regex.lastIndex); // prints "22" var match3 = regex.exec(text); print(match3 === null); // prints "true"
One can test at run-time whether the sticky flag is supported, using try { … } catch { … }. For this, either an eval(…) expression or the RegExp(regex-string, flags-string) syntax must be used (since the /regex/flags notation is processed at compile-time, so throws an exception before the catch block is encountered). For example:
var supports_sticky;
try { RegExp('','y'); supports_sticky = true; }
catch(e) { supports_sticky = false; }
alert(supports_sticky); // alerts "false" in Firefox 2, "true" in Firefox 3
See also
- Regular Expressions chapter in the JavaScript Guide