Regular Expression - Syntax
A regular expression is a powerful tool for matching and manipulating text. It consists of ordinary characters and special characters (called "metacharacters") used to describe the text pattern to be matched.
Regular expressions can find, replace, extract, and validate specific patterns in text.
For example:
-
runoo+b, which can match runoob, runooob, runoooooob etc.,+ The symbol means the preceding character must appear at least once (1 or more times).Try it ».
-
runoo*b, which can match runob, runoob, runoooooob etc.,* The symbol means the preceding character may not appear, or may appear once or multiple times (0, 1, or multiple times).Try it ».
-
colou?r can match color or colour, ? The question mark means the preceding character can appear at most once (0 or 1 time).Try it ».
Constructing a regular expression is like creating a mathematical expression—using various metacharacters and operators, small expressions can be combined to create larger ones. The components of a regular expression can be a single character, a character set, a character range, a choice between characters, or any combination of all these components.
A regular expression acts as a template that matches a certain character pattern against the string being searched.
Ordinary Characters
Ordinary characters include all printable and non-printable characters not explicitly designated as metacharacters, including all uppercase and lowercase letters, all digits, all punctuation marks, and some other symbols.
| Character | Description | Example |
|---|---|---|
| [ABC] |
Matches [...] all the characters listed in . For example, [aeiou] matches all the letters e, o, u, a in the string "google runoob taobao".
|
Try it » |
| [^ABC] |
matches all characters except those in [...] . For example, [^aeiou] matches all characters in the string "google runoob taobao" other than the letters e, o, u, a.
|
Try it » |
| [A-Z] |
[A-Z] represents a range matching all uppercase letters; [a-z] matches all lowercase letters; [0-9] matches all digits.
|
Try it » |
| . |
Matches any single character except a newline (\n, \r), equivalent to [^\n\r].
|
Try it » |
| [\s\S] |
Matches all characters (including newlines).\s Matches all whitespace (including newlines),\S matches all non-whitespace (excluding newlines); combining the two matches any character.
|
Try it » |
| \w |
Matches letters, digits, and underscores, equivalent to [A-Za-z0-9_].
|
Try it » |
| \d |
Matches any Arabic numeral (0 to 9), equivalent to [0-9].
|
Try it » |
Testing Tool
Modifiers:
[0-9]+
Match text:
123abc456edf789
Non-printable Characters
Non-printable characters can also be part of regular expressions. The table below lists the escape sequences representing non-printable characters:
| Character | Description |
|---|---|
| \cx | Matches the control character specified by x. For example, \cM matches a Control-M or carriage return. The value of x must be one of A-Z or a-z, otherwise c is treated as a literal 'c' character. |
| \f | Matches a form feed, equivalent to \x0c and \cL. |
| \n | Matches a newline, equivalent to \x0a and \cJ. |
| \r | Matches a carriage return, equivalent to \x0d and \cM. |
| \s | Matches any whitespace character, including spaces, tabs, form feeds, etc., equivalent to [ \f\n\r\t\v]. Note that Unicode regular expressions also match full-width spaces. |
| \S | Matches any non-whitespace character, equivalent to [^ \f\n\r\t\v]. |
| \t | Matches a tab, equivalent to \x09 and \cI. |
| \v | Matches a vertical tab, equivalent to \x0b and \cK. |
Special characters
Special characters are characters with special meanings, such as the * in runoo*b mentioned above ", which means 'any number of characters'. To find the * symbol itself in a string, you must escape *, by placing a backslash \ before it, so runo*ob matches the string **runoob**.
Many metacharacters require special treatment when attempting to match them. To match these special characters, you must first "escape" the character by placing the backslash character \ before them. The table below lists the special characters in regular expressions:
| Special characters | Description |
|---|---|
| $ | Matches the end position of the input string. If the Multiline property of the RegExp object is set, $ also matches '\n' or '\r'. To match the $ character itself, use \$. |
| ( ) | Marks the start and end positions of a subexpression. A subexpression can be captured for later use. To match these characters, use \( and \). |
| * | Matches the preceding subexpression zero or more times. To match the * character itself, use \*. |
| + | Matches the preceding subexpression one or more times. To match the + character itself, use \+. |
| . | Matches any single character except a newline \n. To match . itself, use \. . |
| [ | Marks the start of a bracket expression. To match [, use \[. |
| ? | Matches the preceding subexpression zero or once, or indicates a non-greedy quantifier. To match the ? character itself, use \?. |
| \ | Marks the next character as a special character, literal character, backreference, or octal escape. For example, 'n' matches the character 'n', '\n' matches a newline, '\\' matches "", and '(' matches "(". |
| ^ | Matches the start position of the input string. When used inside a bracket expression, indicates that the character set inside the brackets is not accepted (negation). To match the ^ character itself, use \^. |
| { | Marks the start of a quantifier expression. To match {, use \{. |
| | | Indicates a choice between two items. To match |, use \| |
Qualifier
Quantifiers are used to specify how many times a given component of a regular expression must appear to satisfy a match. There are six kinds in total: *, +, ?, {n}, {n,}, and {n,m}.
| Character | Description | Example |
|---|---|---|
| * | Matches the preceding subexpression zero or more times. For example, zo* can match "z" and "zoo". * is equivalent to {0,}. | Try it » |
| + | Matches the preceding subexpression one or more times. For example, zo+ can match "zo" and "zoo", but cannot match "z". + is equivalent to {1,}. | Try it » |
| ? |
Matches the preceding subexpression zero or once. For example,do(es)? can match "do" and "does", but cannot match "dog".? is equivalent to {0,1}.
|
Try it » |
| {n} | n is a non-negative integer matching exactly n times. For example, o{2} cannot match "Bob" 's o, but can match "food" 's two o's. | Try it » |
| {n,} | n is a non-negative integer, matching at least n times. For example, o{2,} cannot match "Bob" 's o, but can match "foooood" 's all o's. o{1,} is equivalent to o+, and o{0,} is equivalent to o*. | Try it » |
| {n,m} | Both m and n are non-negative integers, with n <= m. It matches at least n times and at most m times. For example, o{1,3} will match "fooooood" 's first three o's. o{0,1} is equivalent to o?. Note: there must be no space between the comma and the two numbers. | Try it » |
The following regular expression matches a positive integer,[1-9] setting the first digit to be non-zero, and [0-9]* representing any number of digits:
/[1-9][0-9]*/

Note that the quantifier appears after the range expression, so it applies to the entire range expression, specifying in this case only digits from 0 to 9 (inclusive).
The + quantifier is not used here because a digit is not necessarily required in the second or later positions. The ? character is also not used, because using ? would limit the integer to only two digits.
If you want to match a two-digit number from 0 to 99, you can use the following expression to specify at least one and at most two digits:
/[0-9]{1,2}/
The expression above has a drawback: it can only match numbers within two digits, and it would match unexpected values like 0 and 00. The improved expression for matching positive integers from 1 to 99 is as follows:
/[1-9][0-9]?/
or
/[1-9][0-9]{0,1}/
*** and + quantifiers are greedy because they match as much text as possible. Adding a ? after them achieves non-greedy or minimal matching.**
For example, you might search an HTML document to find the content inside h1 tags. The HTML code is as follows:
RUNOOB-Runoob Tutorial
**Greedy:** The following expression matches from the opening less-than symbol (<) to the closing greater-than symbol (>) of the h1 tag, everything in between:
/<.*>/

**Non-greedy:** If you only need to match the opening and closing h1 tags, the following non-greedy expression matches only
:
/<.*?>/

You can also use the following regular expression to match h1 tags:
/<\w+?>/

By placing a ? after the *, +, or ? quantifier, the expression switches from "greedy" to "non-greedy" (minimal matching).
Anchors
Anchors let you fix a regular expression to the start or end of a line, and can also describe the boundaries of words.
^ and $ refer to the start and end of a string respectively, \b describes the boundary before or after a word, and \B indicates a non-word boundary.
| Character | Description | Example |
|---|---|---|
| ^ | Matches the position at the start of the input string. If the Multiline property of the RegExp object is set, ^ also matches the position after \n or \r. | Try it » |
| $ | Matches the position at the end of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before \n or \r. | Try it » |
| \b | Matches a word boundary, i.e., the position between a word and a space. | Try it » |
| \B | Non-word boundary matching, i.e., a position that is not at the beginning or end of a word. | Try it » |
Note:Quantifiers cannot be used together with anchors. Because there can be no more than one position immediately before or after a newline or word boundary, expressions such as ^* such expressions are not allowed.
To match text at the beginning of a line, use the ^ character at the start of the regular expression. Be careful not to confuse this usage of ^ with its negation usage inside bracket expressions.
To match the end of a line of text, use the $ character at the end of the regular expression.
To use anchors when searching for section headings, the following regular expression matches a section heading that contains only two trailing digits and appears at the beginning of a line:
/^Chapter [1-9][0-9]{0,1}/
A true section heading appears not only at the beginning of a line but is also the only text in that line. The following expression limits both the beginning and the end of the line to ensure the specified match matches only section headings and not cross-references:
/^Chapter [1-9][0-9]{0,1}$/
Word boundaries allow precise control over the match range. The following expression matches the first three characters of the word Chapter because these three characters appear after a word boundary:
/\bCha/
The position of \b is very important: when at the beginning of a string, it finds a match at the start of a word; when at the end of a string, it finds a match at the end of a word. For example, the following expression matches the string ter in the word Chapter because it appears before a word boundary:
/ter\b/
The following expression matches the string apt in Chapter but does not match the string apt in aptitude:
/\Bapt/
The string apt appears at a non-word boundary in the word Chapter, but at a word boundary in the word aptitude. For the \B non-word boundary operator, the beginning or end of a word cannot be matched, so the following expression does not match Cha in Chapter:
/\BCha/
Choice
Enclose all alternatives in parentheses () and separate adjacent alternatives with |.
() denotes a capturing group; () saves the matched value within each group, and multiple matched values can be viewed through the number n (where n is a number representing the content of the nth capturing group).


Using parentheses has a side effect: the related matched content is cached (captured). If capturing is not needed, you can place ?: before the first option to eliminate this side effect; in this case the parentheses are used only for grouping and do not save the matched content.
Among these, ?: is one of the non-capturing metacharacters; the other two non-capturing metacharacters are ?= and ?!: the former is a positive lookahead, matching the search string at any position where the regular expression pattern inside the parentheses begins to match; the latter is a negative lookahead, matching the search string at any position where that pattern does not begin to match.
?=, ?<=, ?!, ?
exp1(?=exp2): find exp1 preceding exp2 (positive lookahead).

(?<=exp2)exp1: find exp1 following exp2 (positive lookbehind).

exp1(?!exp2): find exp1 not followed by exp2 (negative lookahead).

(?

For more information, refer to:Lookahead and lookbehind assertions in regular expressions.
Backreference
Adding parentheses around a regular expression pattern or part of a pattern causes the related match to be stored in a temporary buffer. Each captured submatch is stored in the order it appears from left to right in the regular expression pattern, with buffer numbering starting at 1 and storing up to 99 captured subexpressions. Each buffer can be accessed using \n, where n is a one- or two-digit decimal number identifying a specific buffer.
You can use the non-capturing metacharacters ?:, ?=, or ?! to rewrite the capture and ignore saving the related match.
One of the simplest and most useful applications of backreferences is finding two identical adjacent words in text. Take the following sentence as an example:
Is is the cost of of gasoline going up up?
The sentence above contains several repeated words. The following regular expression uses a single subexpression to locate these repetitions:
Example
Find duplicate words:
var
str
=
"Is is the cost of of gasoline going up up"
;
var
patt1
=
/\b([a-z]+) \1\b/igm
;
document.
write
(
str.
match
(
patt1
)
)
;
Try it »
The captured expression [a-z]+ matches one or more letters. The second part of the regular expression, \1, is a backreference to the first submatch (the content captured in parentheses), meaning it requires a word immediately following that is the same as the first word.
The word boundary metacharacter \b ensures that only whole words are detected; otherwise phrases like "is issued" or "this is" would not be correctly recognized.
The g (global) flag at the end of the expression specifies that the expression is applied to all matches found in the input string; the i (ignore case) flag specifies case-insensitive matching; the m (multiline) flag specifies that potential matches may occur on either side of a newline.
Backreferences can also decompose a URI into its components. Suppose you want to decompose the following URI into protocol (ftp, http, etc.), domain address, and path:
https://www.runoob.com:80/html/html-tutorial.html
The following regular expression provides this functionality:
Example
Output all matched data:
var
str
=
"https://www.runoob.com:80/html/html-tutorial.html"
;
var
patt1
=
/
(
\w
)
:
\
/
\
/
(
[
^
/:]+)(:\d*)?([^# ]*)/
;
arr
=
str.
match
(
patt1
)
;
for
(
var
i
=
0
;
i
<
arr.
length
;
i
++
)
{
document.
write
(
arr
[
i
]
)
;
document.
write
(
"
"
)
;
}
Try it »
str.match(patt1) Returns an array containing 5 elements: index 0 corresponds to the entire matched string, and indexes 1 through 4 correspond to the respective parenthesized capture groups, and so on.
- The first parenthesized subexpression(\w+): captures the protocol part of a Web address, matching any word before the colon and two forward slashes. Result:https
- The second parenthesized subexpression([^/:]+): captures the domain address part, matching one or more characters that are not : and /. Result:www.runoob.com
- The third parenthesized subexpression(:\d*): captures the port number (if present), matching zero or more digits after the colon. Result::80
- The fourth parenthesized subexpression([^# ]*): captures the path and page information, matching any sequence of characters that does not include # or a space. Result:/html/html-tutorial.html