在 JavaScript 中,**Reg**ular **Ex**pression(RegEx)是一个对象,用于描述用于定义搜索模式的字符序列。例如,
/^a...s$/
上面的代码定义了一个 RegEx 模式。该模式是:**以** a
**开头并以** s
**结尾的任意五个字母的字符串**。
使用 RegEx 定义的模式可以用来匹配 字符串。
表达式 | 字符串 | 匹配? |
---|---|---|
/^a...s$/ |
abs |
无匹配 |
alias |
匹配 | |
abyss |
匹配 | |
Alias |
无匹配 | |
An abacus |
无匹配 |
创建 RegEx
在 JavaScript 中创建正则表达式有两种方法。
- 使用正则表达式字面量
正则表达式由一对斜杠/
之间的模式组成。例如,
这里,const regularExp = /abc/;
/abc/
是一个正则表达式。 - 使用
RegExp()
构造函数
您还可以通过调用RegExp()
构造函数来创建正则表达式。例如,const regularExp = new RegExp('abc');
例如,
const regex = new RegExp(/^a...s$/);
console.log(regex.test('alias')); // true
在上面的示例中,字符串 alias
匹配 RegEx 模式 /^a...s$/
。这里,test()
方法用于检查字符串是否与模式匹配。
JavaScript RegEx 有其他几种可用的方法。在进一步探讨它们之前,让我们先了解一下正则表达式本身。
如果您已经了解 RegEx 的基础知识,请跳转到 JavaScript RegEx 方法。
使用 RegEx 指定模式
要指定正则表达式,需要使用元字符。在上面的示例(/^a...s$/
)中,^
和 $
是元字符。
元字符
元字符是 RegEx 引擎以特殊方式解释的字符。这是一个元字符列表
[] . ^ $ * + ? {} () \ |
[]
- 方括号
方括号指定您希望匹配的字符集。
表达式 | 字符串 | 匹配? |
---|---|---|
[abc] |
a |
1 匹配 |
ac |
2 个匹配 | |
Hey Jude |
无匹配 | |
abc de ca |
5 匹配 |
在这里,[abc]
将在您尝试匹配的字符串包含 a
、b
或 c
中的任何一个时匹配。
您还可以使用方括号内的 -
来指定字符范围。
[a-e]
与 [abcde]
相同。
[1-4]
等同于 [1234]
。
[0-39]
等同于 [01239]
。
您可以通过在方括号开头使用插入符 ^
符号来补充(反转)字符集。
[^abc]
表示除 a
、b
或 c
之外的任何字符。
[^0-9]
表示任何非数字字符。
.
- 点
点匹配任何单个字符(换行符 '\n'
除外)。
表达式 | 字符串 | 匹配? |
---|---|---|
.. |
a |
无匹配 |
ac |
1 匹配 | |
acd |
1 匹配 | |
acde |
2 匹配(包含 4 个字符) |
^
- 插入符
插入符符号 ^
用于检查字符串**是否以**特定字符开头。
表达式 | 字符串 | 匹配? |
---|---|---|
^a |
a |
1 匹配 |
abc |
1 匹配 | |
bac |
无匹配 | |
^ab |
abc |
1 匹配 |
acb |
无匹配(以 a 开头但不跟 b ) |
$
- 美元符号
美元符号 $
用于检查字符串**是否以**特定字符结尾。
表达式 | 字符串 | 匹配? |
---|---|---|
a$ |
a |
1 匹配 |
formula |
1 匹配 | |
cab |
无匹配 |
*
- 星号
星号符号 *
匹配其左侧模式的**零个或多个**出现。
表达式 | 字符串 | 匹配? |
---|---|---|
ma*n |
mn |
1 匹配 |
man |
1 匹配 | |
mann |
1 匹配 | |
main |
无匹配(a 后面没有 n ) |
|
woman |
1 匹配 |
+
- 加号
加号符号 +
匹配其左侧模式的一个或多个出现。
表达式 | 字符串 | 匹配? |
---|---|---|
ma+n |
mn |
无匹配(没有 a 字符) |
man |
1 匹配 | |
mann |
1 匹配 | |
main |
无匹配(a 后面没有 n ) |
|
woman |
1 匹配 |
?
- 问号
问号符号 ?
匹配其左侧模式的**零个或一个**出现。
表达式 | 字符串 | 匹配? |
---|---|---|
ma?n |
mn |
1 匹配 |
man |
1 匹配 | |
maan |
无匹配(超过一个 a 字符) |
|
main |
无匹配(a 后面没有 n ) |
|
woman |
1 匹配 |
{}
- 花括号
考虑这段代码:{n,m}
。这意味着其左侧模式的重复次数至少为 n
,最多为 m
。
表达式 | 字符串 | 匹配? |
---|---|---|
a{2,3} |
abc dat |
无匹配 |
abc daat |
1 匹配(在 daat 处) |
|
aabc daaat |
2 匹配(在 aabc 和 daaat 处) |
|
aabc daaaat |
2 匹配(在 aabc 和 daaaat 处) |
再举一个例子。这个 RegEx [0-9]{2, 4}
匹配至少 2 位数字,但不超过 4 位数字。
表达式 | 字符串 | 匹配? |
---|---|---|
[0-9]{2,4} |
ab123csde |
1 匹配(在 ab123csde 处匹配) |
12 and 345673 |
3 匹配(12 、3456 、73 ) |
|
1 and 2 |
无匹配 |
|
- 交替
竖线 |
用于交替(或
运算符)。
表达式 | 字符串 | 匹配? |
---|---|---|
a|b |
cde |
无匹配 |
ade |
1 匹配(在 ade 处匹配) |
|
acdbea |
3 匹配(在 acdbea 处) |
这里,a|b
匹配任何包含 a
或 b
的字符串
()
- 分组
括号 ()
用于对子模式进行分组。例如,(a|b|c)xz
匹配任何以 xz
结尾且前面是 a
、b
或 c
的字符串
表达式 | 字符串 | 匹配? |
---|---|---|
(a|b|c)xz |
ab xz |
无匹配 |
abxz |
1 匹配(在 abxz 处匹配) |
|
axz cabxz |
2 匹配(在 axzbc cabxz 处) |
\
- 反斜杠
反斜杠 \
用于转义各种字符,包括所有元字符。例如,
\$a
匹配字符串包含 $
后跟 a
的情况。这里,$
不会被 RegEx 引擎以特殊方式解释。
如果您不确定一个字符是否有特殊含义,可以在其前面加上 \
。这可以确保该字符不会被以特殊方式处理。
特殊序列
特殊序列使常用的模式更容易编写。这是一个特殊序列列表
\A
- 当指定的字符位于字符串开头时匹配。
表达式 | 字符串 | 匹配? |
---|---|---|
\Athe |
the sun |
匹配 |
In the sun |
无匹配 |
\b
- 当指定的字符位于单词的开头或结尾时匹配。
表达式 | 字符串 | 匹配? |
---|---|---|
\bfoo |
football |
匹配 |
a football |
匹配 | |
foo\b |
a football |
无匹配 |
the foo |
匹配 | |
the afoo test |
匹配 | |
the afootest |
无匹配 |
\B
- 与 \b
相反。当指定的字符不在单词的开头或结尾时匹配。
表达式 | 字符串 | 匹配? |
---|---|---|
\Bfoo |
football |
无匹配 |
a football |
无匹配 | |
foo\B |
a football |
匹配 |
the foo |
无匹配 | |
the afoo test |
无匹配 | |
the afootest |
匹配 |
\d
- 匹配任何十进制数字。等同于 [0-9]
表达式 | 字符串 | 匹配? |
---|---|---|
\d |
12abc3 |
3 匹配(在 12abc3 处) |
JavaScript |
无匹配 |
\D
- 匹配任何非十进制数字。等同于 [^0-9]
表达式 | 字符串 | 匹配? |
---|---|---|
\D |
1ab34"50 |
3 匹配(在 1ab34"50 处) |
1345 |
无匹配 |
\s
- 匹配字符串中包含任何空白字符的地方。等同于 [ \t\n\r\f\v]
。
表达式 | 字符串 | 匹配? |
---|---|---|
\s |
JavaScript RegEx |
1 匹配 |
JavaScriptRegEx |
无匹配 |
\S
- 匹配字符串中包含任何非空白字符的地方。等同于 [^ \t\n\r\f\v]
。
表达式 | 字符串 | 匹配? |
---|---|---|
\S |
a b |
2 匹配(在 a b 处) |
无匹配 |
\w
- 匹配任何字母数字字符(数字和字母)。等同于 [a-zA-Z0-9_]
。顺便说一下,下划线 _
也被认为是字母数字字符。
表达式 | 字符串 | 匹配? |
---|---|---|
\w |
12&": ;c |
3 匹配(在 12&": ;c 处) |
%"> ! |
无匹配 |
\W
- 匹配任何非字母数字字符。等同于 [^a-zA-Z0-9_]
表达式 | 字符串 | 匹配? |
---|---|---|
\W |
1a2%c |
1 匹配(在 1a2%c 处) |
JavaScript |
无匹配 |
\Z
- 当指定的字符位于字符串结尾时匹配。
表达式 | 字符串 | 匹配? |
---|---|---|
JavaScript\Z |
I like JavaScript |
1 匹配 |
I like JavaScript Programming |
无匹配 | |
JavaScript is fun |
无匹配 |
**提示**:要构建和测试正则表达式,您可以使用 RegEx 测试工具,例如 regex101。此工具不仅可以帮助您创建正则表达式,还可以帮助您学习它。
现在您已经了解了 RegEx 的基础知识,让我们讨论一下如何在 JavaScript 代码中使用 RegEx。
JavaScript 正则表达式方法
如上所述,您可以使用 RegExp()
或正则表达式字面量在 JavaScript 中创建 RegEx。
const regex1 = /^ab/;
const regex2 = new Regexp('/^ab/');
在 JavaScript 中,您可以使用 RegExp()
方法:test()
和 exec()
来处理正则表达式。
还有一些 字符串方法允许您将 RegEx 作为参数传递。它们是:match()
、replace()
、search()
和 split()
。
方法 | 描述 |
---|---|
exec() |
在字符串中执行匹配搜索并返回一个信息数组。不匹配时返回 null。 |
test() |
测试字符串中的匹配项,并返回 true 或 false。 |
match() | 返回一个包含所有匹配项的数组。不匹配时返回 null。 |
matchAll() | 返回一个包含所有匹配项的迭代器。 |
search() | 测试字符串中的匹配项,并返回匹配项的索引。如果搜索失败,则返回 -1。 |
replace() | 在字符串中搜索匹配项,并将匹配的子字符串替换为替换子字符串。 |
split() | 将字符串分解为子字符串数组。 |
示例 1:正则表达式
const string = 'Find me';
const pattern = /me/;
// search if the pattern is in string variable
const result1 = string.search(pattern);
console.log(result1); // 5
// replace the character with another character
const string1 = 'Find me';
string1.replace(pattern, 'found you'); // Find found you
// splitting strings into array elements
const regex1 = /[\s,]+/;
const result2 = 'Hello world! '.split(regex1);
console.log(result2); // ['Hello', 'world!', '']
// searching the phone number pattern
const regex2 = /(\d{3})\D(\d{3})-(\d{4})/g;
const result3 = regex2.exec('My phone number is: 555 123-4567.');
console.log(result3); // ["555 123-4567", "555", "123", "4567"]
正则表达式标志
标志用于正则表达式,它们允许各种选项,如全局搜索、不区分大小写的搜索等。它们可以单独使用,也可以组合使用。
标志 | 描述 |
---|---|
g |
执行全局匹配(查找所有匹配项) |
m |
执行多行匹配 |
i |
执行不区分大小写的匹配 |
示例 2:正则表达式修饰符
const string = 'Hello hello hello';
// performing a replacement
const result1 = string.replace(/hello/, 'world');
console.log(result1); // Hello world hello
// performing global replacement
const result2 = string.replace(/hello/g, 'world');
console.log(result2); // Hello world world
// performing case-insensitive replacement
const result3 = string.replace(/hello/i, 'world');
console.log(result3); // world hello hello
// performing global case-insensitive replacement
const result4 = string.replace(/hello/gi, 'world');
console.log(result4); // world world world
示例 3:验证手机号码
// program to validate the phone number
function validatePhone(num) {
// regex pattern for phone number
const re = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/g;
// check if the phone number is valid
let result = num.match(re);
if (result) {
console.log('The number is valid.');
}
else {
let num = prompt('Enter number in XXX-XXX-XXXX format:');
validatePhone(num);
}
}
// take input
let number = prompt('Enter a number XXX-XXX-XXXX');
validatePhone(number);
输出
Enter a number XXX-XXX-XXXX: 2343223432 Enter number in XXX-XXX-XXXX format: 234-322-3432 The number is valid
示例 4:验证电子邮件地址
// program to validate the email address
function validateEmail(email) {
// regex pattern for email
const re = /\S+@\S+\.\S+/g;
// check if the email is valid
let result = re.test(email);
if (result) {
console.log('The email is valid.');
}
else {
let newEmail = prompt('Enter a valid email:');
validateEmail(newEmail);
}
}
// take input
let email = prompt('Enter an email: ');
validateEmail(email);
输出
Enter an email: hellohello Enter a valid email: [email protected] The email is valid.