In regular expressions, square brackets []
are metacharacters used to define a set of characters. It has the following effects in regular expressions:
-
Match any character in the character set : the characters listed in square brackets indicate that any of these characters can be matched at this position. For example,
[abc]
will match where any one of the characters is "a", "b", or "c". -
Specify a range of characters : A hyphen can be used
-
to specify a range of characters. For example,[0-9]
means to match any numeric character, which is equivalent to\d
. -
Negated character set : Use the symbol at the beginning of the square brackets
^
to indicate a negative character set. For example,[^0-9]
means to match any non-numeric character. -
Escape special characters : In square brackets, some special characters such as
^
,-
,]
,\
etc. can be used directly without escaping.
Here are some common usage examples:
[abc]
: Match any one of "a", "b" or "c".[0-9]
: Match any one numeric character.[a-z]
: Match any lowercase letter.[A-Z]
: Match any uppercase letter.[a-zA-Z]
: Match any letter (case is not limited).[0-9a-f]
: Match any hexadecimal character.[^0-9]
: Match any non-numeric character.
Square brackets []
are very commonly used in regular expressions, which allow us to define the set of characters that need to be matched, thus providing a flexible matching method. Note that within square brackets, each character generally represents a single character.