Regular Expressions -Examples

Simple expressions

The simplest form of a regular expression is a single ordinary character that matches itself in the search string.

For example, a single-character pattern such as a always matches the letter a wherever it appears in the search string. Below are some examples of single-character regular expression patterns:

Examples

/a/
/b/
/c/

Try it »

The regular expression will exactly match the string "abc". No matter where the string appears in the text, it will succeed only when it exactly matches "abc".

Examples

/abc/

Try it »

Note that this is a very simple example because the string "abc" itself has no special metacharacters or patterns. Therefore, you can use it directly as a regular expression without additional escapes or quantifiers.

Character matching

Wildcards.

Dot.Matches any single character except newline.\nand\rThe following regular expression matches aac, abc, acc, adc, etc., as well as a1c, a2c, a-c, and a#c:

Examples

/a.c/

Try it »

To match a string containing a filename where the period.is part of the input string, prepend a backslash to the period in the regular expression.\character. For example, the following regular expression matches filename.ext:

/filename\.ext/

Quantifiers*

Matches the preceding element zero or more times:

Examples

/a*b/

Try it »

This expression can match strings such as "b", "ab", "aab", "aaab", etc.

Quantifiers+

Matches the preceding element one or more times:

Examples

/a+b/

Try it »

This expression can match strings such as "ab", "aab", "aaab", etc., but does not match "b".

Quantifiers?

Matches the preceding element zero or one time:

Examples

/colou?r/

Try it »

This expression can match "color" or "colour".

The above are some common examples of single-character pattern matching. They can be used to flexibly match and search strings with different patterns.

Please note that regular expression syntax may vary depending on the programming language and tool, so please refer to the corresponding documentation when using it in practice.


A reasonable username regular expression

A username can contain the following types of characters:

  • 1. 26 uppercase and lowercase English letters are represented asa-zA-Z。
  • 2. Digits are represented as0-9。
  • 3. Underscore is represented as_。
  • 4. Hyphen is represented as-。

A username consists of a number of letters, digits, underscores, and hyphens, so you need to use+to represent1one or more occurrences.

Based on the above conditions, the expression for a username can be:

[a-zA-Z0-9_-]+

Examples

var str = "abc123-_def"; var patt = /[a-zA-Z0-9_-]+/; document.write(str.match(patt));

The following marked text is the expression that obtained the matches:

abc123-_def

Try it »

If hyphens are not needed, it is:

[a-zA-Z0-9_]+

Examples

var str = "abc123def"; var str2 = "abc123_def"; var patt = /[a-zA-Z0-9_]+/; document.write(str.match(patt)); document.write(str2.match(patt));

The following marked text is the expression that obtained the matches:

abc123def
abc123_def

Try it »

Matching HTML tags and content

The following regular expression is used to match iframe tags:

/<iframe(([\s\S])*?)<\/iframe>/

For matching other tags, you can replaceiframe 。

Match a div tag with id="mydiv":

/<div id="mydiv"(([\s\S])*?)<\/div>/

Match all img tags:

Examples

/<img.*?src="(.*?)".*?\/?>/gi

Try it »

Bracket expressions

To create a list that matches a group of characters, use square brackets[ ]Place one or more single characters inside them. When characters are enclosed in square brackets, the list is called a "bracket expression". As anywhere else, ordinary characters represent themselves inside square brackets, that is, they match themselves 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[bracket.
  • \The character continues to serve as an escape character. To match the\character, use\\。

Characters enclosed in a bracket expression match only a single character at that position in the regular expression. The following regular expression matches Chapter 1, Chapter 2, Chapter 3, Chapter 4, and Chapter 5:

/Chapter [12345]/

Note that the positions of the word Chapter and the space after it are fixed relative to the characters inside the square brackets. The bracket expression specifies only the set of characters 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 listing characters themselves to represent a group of matching characters, use a hyphen-to separate the starting and ending characters of the range. The character values of the individual characters determine the relative order within the range. The following regular expression contains a range expression that is equivalent to the list in the square brackets shown above.

/Chapter [1-5]/

When specifying a range in this way, both the starting value and the ending value are included in the range. Note that it is also important that the starting value must come before the ending value in Unicode collation order.

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. Both of the following regular expressions meet this requirement:
    [!--]
    [!-~]
    

To find all characters not in the list or range, place the caret^at the beginning of the list. If the caret character appears anywhere else in the list, it matches itself. The following regular expression matches any digit or character other than 1, 2, 3, 4, or 5:

/Chapter [^12345]/

In the example above, the expression matches any digit or character other than 1, 2, 3, 4, or 5 at the ninth position. Thus, for example, Chapter 7 is a match, and Chapter 9 is also a match.

The above expression can use a hyphen-to represent:

/Chapter [^1-5]/

A typical use of a bracket expression 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]/

Alternation and grouping

Alternation uses the|character to allow a choice between two or more alternation options. For example, you could expand the chapter heading regular expression to return matches broader than chapter headings. However, this is not as simple as you might think. Alternation matches|the largest expression on either side of the character.

You might think that the following expression matches Chapter or Section appearing at the beginning or end of a line, followed by one or two digits:

/^Chapter|Section [1-9][0-9]{0,1}$/

Unfortunately, the above regular expression either matches the word Chapter at the beginning of a line, or the word Section at the end of a line along with any digits following it. If the input string is Chapter 22, the above expression only matches the word Chapter. If the input string is Section 22, the expression matches Section 22.

To make the regular expression more controllable, you can use parentheses to limit the scope of the alternation, that is, ensure that 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 in the appropriate places in the above regular expression, you can make it match Chapter 1 or Section 3.

The following regular expression 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 will also capture either of the two matched words for later use. Since there is only one group of parentheses in the above expression, there is only one captured "submatch".

In the above example, you simply use parentheses to group the choice between the words Chapter and Section. To prevent the match from being saved for future use, place?:. The following modification provides the same capability without saving submatches:

/^(?:Chapter|Section) [1-9][0-9]{0,1}$/

divide?:Besides metacharacters, two other non-capturing metacharacters create something called "lookahead" matching. Positive lookahead uses?=to specify; it matches a search string at the starting point of the regular expression pattern within the parentheses. Negative lookahead uses?!to specify; it matches a search string at the starting point of a string that does not match the regular expression pattern.

For example, suppose you have a document that contains references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Further suppose that you need to update the document to change all references to Windows 95, Windows 98, and Windows NT to Windows 2000. The following regular expression (an example of positive lookahead) matches Windows 95, Windows 98, and Windows NT:

/Windows(?=95 |98 |NT )/

After a match is found, the next match is searched immediately after the matched text (not including the characters in the lookahead). For example, if the above expression matches Windows 98, the search continues after Windows rather than after 98.

Other examples

The following lists some regular expression examples:

Regular Expression Description
/\b([a-z]+) \1\b/gi Matches a position where a word appears consecutively.
/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/ Matches a URL parsed into protocol, domain, port, and relative path.
/^(?:Chapter|Section) [1-9][0-9]{0,1}$/ Locates the position of a section.
/[-a-z]/ The 26 letters from a to z, plus one-sign.
/ter\b/ Matches chapter but not terminal.
/\Bapt/ Matches chapter but not aptitude.
/Windows(?=95 |98 |NT )/ Matches Windows95, Windows98, or WindowsNT; after a match is found, the next search begins after Windows.
/^\s*$/ Matches blank lines.
/\d{2}-\d{5}/ Validates an ID consisting of two digits, a hyphen, and five digits.
<[a-zA-Z]+.*?>([\s\S]*?)</[a-zA-Z]*?> Matches HTML tags.
Regular ExpressionDescription
hello Matches {hello}
gray|grey Matches {gray, grey}
gr(a|e)y Matches {gray, grey}
gr[ae]y Matches {gray, grey}
b[aeiou]bble Matches {babble, bebble, bibble, bobble, bubble}
[b-chm-pP]at|ot Matches {bat, cat, hat, mat, nat, oat, pat, Pat, ot}
colou?r Matches {color, colour}
rege(x(es)?|xps?) Matches {regex, regexes, regexp, regexps}
go*gle Matches {ggle, gogle, google, gooogle, goooogle, ...}
go+gle Matches {gogle, google, gooogle, goooogle, ...}
g(oog)+le Matches {google, googoogle, googoogoogle, googoogoogoogle, ...}
z{3} Matches {zzz}
z{3,6} Matches {zzz, zzzz, zzzzz, zzzzzz}
z{3,} Matches {zzz, zzzz, zzzzz, ...}
[Bb]rainf\*\*k Matches {Brainf**k, brainf**k}
\d Matches {0,1,2,3,4,5,6,7,8,9}
1\d{10} Matches 11 digits starting with 1
[2-9]|[12]\d|3[0-6] Matches integers in the range 2 to 36
Hello\nworld Matches Hello followed by a newline, followed by world
\d+(\.\d\d)? Contains a positive integer or a floating-point number with two decimal places.
[^*@#] Excludes the three special symbols *, @, and #
//[^\r\n]*[\r\n] Matches//comments beginning with
^dog Matches strings beginning with "dog"
dog$ Matches strings ending with "dog"
^dog$ is exactly "dog"

More examples

  • Chinese Regular Expressions

  • License plate number regular expression

  • WeChat ID regular expression

  • QQ number regular expression

  • Hexadecimal color regular expression

  • Password strength regular expression

  • Username regular expression

  • Email regular expression

Other extensions