Regular Expression - Examples
Simple expressions
The simplest form of a regular expression is to match a single ordinary character itself within the searched string.
For example, a single-character pattern such as a always matches the letter a wherever it appears in the searched string. Here are some examples of single-character regex patterns:
Example
/a/
/b/
/c/
Try it »
The regex will exactly match the string "abc" wherever it appears in the text, and it only succeeds when it fully matches "abc".
Example
/abc/
Try it »
Note that this is a very simple example because the string "abc" itself contains no special metacharacters or patterns. Therefore, you can use it directly as a regex without additional escaping or quantifiers.
Character matching
Wildcard .
The dot . matches any single character except the newline characters \n and \r. The following regex matches aac, abc, acc, adc, etc., as well as a1c, a2c, a-c, and a#c:
Example
/a.c/
Try it »
To match a string containing a filename where the period . is part of the input string, place a backslash \ character before the period in the regex. For example, the following regex matches filename.ext:
/filename\.ext/
Quantifier *
Matches the preceding element zero or more times:
Example
/a*b/
Try it »
This expression can match strings such as "b", "ab", "aab", "aaab", etc.
Quantifier +
Matches the preceding element one or more times:
Example
/a+b/
Try it »
This expression can match strings such as "ab", "aab", "aaab", etc., but does not match "b".
Quantifier ?
Matches the preceding element zero or one time:
Example
/colou?r/
Try it »
This expression can match "color" or "colour".
The above are some common examples of single-character pattern matching, which can be used to flexibly match and search strings with different patterns.
Note that regex syntax may vary by programming language and tool, so please refer to the corresponding documentation when actually using it.
A reasonable username regex
A username may contain the following types of characters:
- 1. The 26 uppercase and lowercase English letters are represented as a-zA-Z.
- 2. Digits are represented as 0-9.
- 3. The underscore is represented as _.
- 4. The hyphen is represented as -.
A username is composed of several letters, digits, underscores, and hyphens, so + is needed to represent 1 one or more occurrences.
Based on the above conditions, the expression for a username can be:
[a-zA-Z0-9_-]+
Example
var
str
=
"
abc123-_def
"
;
var
patt
= /
[
a
zA
Z0
9
_
]
+/;
document
.
write
(
str
.
match
(
patt
)
)
;
The text marked below is the expression that obtains the match:
abc123-_def
Try it »
If the hyphen is not needed, it becomes:
[a-zA-Z0-9_]+
Example
var
str
=
"
abc123def
"
;
var
str2
=
"
abc123_def
"
;
var
patt
= /
[
a
zA
Z0
9
_
]
+/;
document
.
write
(
str
.
match
(
patt
)
)
;
document
.
write
(
str2
.
match
(
patt
)
)
;
The text marked below is the expression that obtains the match:
abc123def
abc123_def
Try it »
Match HTML tags and content
The following regex is used to match the iframe tag:
/
For other tags, you can replace iframe.
Match the div tag with id="mydiv":
//
Match all img tags:
Example
/?src="(.?)".*?/?>/gi
Try it »
Bracket expressions
To create a list that matches a group of characters, place one or more single characters inside square brackets [ ]. When characters are enclosed in square brackets, the list is called a "bracket expression". As elsewhere, an ordinary character inside brackets represents itself, that is, it matches itself once in the input text. Most special characters lose their meaning when they appear inside a bracket expression. However, there are some exceptions, such as:
- If the ] character is not the first item, it ends a list. To match the ] character in the list, place it first, immediately after the opening [.
- The \ character continues to act as an escape character. To match the \ character, use \.
A character enclosed in a bracket expression matches only a single character at that position in the regex. The following regex matches Chapter 1, Chapter 2, Chapter 3, Chapter 4, and Chapter 5:
/Chapter [12345]/
Note that the position of the word Chapter and the following space is fixed relative to the characters inside the brackets. The bracket expression specifies only the character set that matches the single character position immediately following the word Chapter and the space. This is the ninth character position.
To use a range instead of the characters themselves to represent a matched character group, use a hyphen - to separate the starting and ending characters of the range. The character value of a single character determines the relative order within the range. The following regex contains a range expression equivalent to the list in the brackets shown above.
/Chapter [1-5]/
When a range is specified in this way, both the start and end values are included in the range. Also note that, by Unicode sort order, the start value must come before the end value.
To include a hyphen in a bracket expression, use one of the following methods:
- Escape it with a backslash:
[-]
- Place the hyphen at the beginning or end of the bracket list. The following expression matches all lowercase letters and the hyphen:
[-a-z]
[a-z-]
- Create a range in which the starting character value is less than the hyphen and the ending character value is equal to or greater than the hyphen. The following two regexes both satisfy this requirement:
[!--]
[!-~]
To find all characters that are not in the list or range, place the caret ^ at the beginning of the list. If the caret appears anywhere else in the list, it matches itself. The following regex matches any digit or character other than 1, 2, 3, 4, or 5:
/Chapter [^12345]/
In the example above, the expression matches at the ninth position any digit or character other than 1, 2, 3, 4, or 5. Thus, for example, Chapter 7 is a match, and Chapter 9 is also a match.
The expression above can be represented using a hyphen -:
/Chapter [^1-5]/
A typical use of bracket expressions is to specify a match for any uppercase or lowercase letter or any digit. The following expression specifies such a match:
/[A-Za-z0-9]/
Substitution and grouping
Substitution uses the | character to allow a choice between two or more alternatives. For example, you can extend the chapter-title regex to return matches broader than the chapter-title range. However, this is not as simple as you might think. Substitution matches the largest expression on either side of the | character.
You might think the following expression matches Chapter or Section appearing at the beginning and end of a line, followed by one or two digits:
/^Chapter|Section [1-9][0-9]{0,1}$/
Unfortunately, the regex above either matches the word Chapter at the beginning of a line or matches the word Section at the end of a line along with any digits following it. If the input string is Chapter 22, the expression above matches only the word Chapter. If the input string is Section 22, the expression matches Section 22.
To make the regex easier to control, you can use parentheses to limit the scope of the substitution, that is, ensure it applies only to the two words Chapter and Section. However, parentheses are also used to create subexpressions and may capture them for later use, as described in the section on backreferences. By adding parentheses at the appropriate positions in the regex above, you can make it match Chapter 1 or Section 3.
The following regex uses parentheses to group Chapter and Section so that the expression works correctly:
/^(Chapter|Section) [1-9][0-9]{0,1}$/
Although these expressions work correctly, the parentheses around Chapter|Section also capture either of the two matched words for later use. Since there is only one set of parentheses in the expression above, there is only one captured "submatch".
In the example above, you only need to use parentheses to group the choice between the words Chapter and Section. To prevent the match from being saved for later use, place ?: before the regex pattern inside the parentheses. The modification below provides the same capability without saving the submatch:
/^(?:Chapter|Section) [1-9][0-9]{0,1}$/
Besides the ?: metacharacter, two other non-capturing metacharacters create what is called a "predictive lookahead" match. Positive lookahead uses ?= to specify that it matches a search string at the starting point of the regex pattern matched within the parentheses. Negative lookahead uses ?! to specify that it matches a search string at the starting point of a string that does not match the regex pattern.
For example, suppose you have a document that contains references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Further suppose you need to update the document, changing all references to Windows 95, Windows 98, and Windows NT to Windows 2000. The following regex (an example of positive lookahead) matches Windows 95, Windows 98, and Windows NT:
/Windows(?=95 |98 |NT )/
After finding one match, the search for the next match immediately continues after the matched text (excluding the characters in the lookahead). For example, if the expression above matches Windows 98, the search continues after Windows rather than after 98.
Other examples
Some regex examples are listed below:
Regular expressions
Description
/\b([a-z]+) \1\b/gi
The position where a word appears consecutively.
/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/
Match a URL parsed into protocol, domain, port, and relative path.
/^(?:Chapter\|Section) [1-9][0-9]{0,1}$/
Locate the position of a chapter.
/[-a-z]/
Letters a through z, 26 letters in total, plus a - sign.
/ter\b/
Can match chapter, but cannot match terminal.
/\Bapt/
Can match chapter, but cannot match aptitude.
/Windows(?=95 \|98 \|NT )/
Can match Windows95, Windows98, or WindowsNT; after finding a match, the next search begins after Windows.
/^\s*$/
Match an empty line.
/\d{2}-\d{5}/
Validate an ID number consisting of two digits, a hyphen, and then five digits.
<[a-zA-Z]+.*?>([\s\S]*?)
Match HTML tags.
Regular expressions
Description
hello
Match {hello}
gray\|grey
Match {gray, grey}
gr(a\|e)y
Match {gray, grey}
gr[ae]y
Match {gray, grey}
b[aeiou]bble
Match {babble, bebble, bibble, bobble, bubble}
[b-chm-pP]at\|ot
Match {bat, cat, hat, mat, nat, oat, pat, Pat, ot}
colou?r
Match {color, colour}
rege(x(es)?\|xps?)
Match {regex, regexes, regexp, regexps}
go*gle
Match {ggle, gogle, google, gooogle, goooogle, ...}
go+gle
Match {gogle, google, gooogle, goooogle, ...}
g(oog)+le
Match {google, googoogle, googoogoogle, googoogoogoogle, ...}
z{3}
Match {zzz}
z{3,6}
Match {zzz, zzzz, zzzzz, zzzzzz}
z{3,}
Match {zzz, zzzz, zzzzz, ...}
[Bb]rainf\*\*k
Match {Brainfk, brainfk}
\d
Match {0,1,2,3,4,5,6,7,8,9}
1\d{10}
Match 11 digits starting with 1
[2-9]\|[12]\d\|3[0-6]
Match integers in the range 2 to 36
Hello\nworld
Match Hello followed by a newline, followed by world
\d+(\.\d\d)?
Contains a positive integer or a floating-point number with two decimal places.
[^*@#]
Exclude the three special symbols *, @, and #
//[^\r\n]*[\r\n]
Match comments starting with //
^dog
Match strings starting with "dog"
dog$
Match strings ending with "dog"
^dog$
is exactly "dog"
More examples