在JavaScript中,一个寄存器 ular 例 PRESSION(正则表达式)是描述用于定义搜索模式的字符序列中的对象。例如,
/^a...s$/
上面的代码定义了RegEx模式。模式是: 以 a
开头 并以 s
结尾的 任何五个字母字符串 。
使用RegEx定义的模式可用于与字符串匹配。
Expression | String | Matched? |
---|---|---|
/^a...s$/ |
abs |
No match |
alias |
Match | |
abyss |
Match | |
Alias |
No match | |
An abacus |
No match |
创建一个正则表达式
您可以通过两种方式在JavaScript中创建正则表达式。
- 使用正则表达式字面量:
正则表达式由包含在斜杠/
之间的模式组成。例如,cost regularExp = /abc/;
/abc/
是一个正则表达式。 - 使用
RegExp()
构造函数 :
您还可以通过调用RegExp()
构造函数来创建正则表达式。例如,const reguarExp = 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 Methods。
使用正则表达式指定模式
为了指定正则表达式,使用了元字符。在上面的示例( /^a...s$/
)中, ^
和$
是元字符。
元字符
元字符是在一种特殊的方式用正则表达式引擎解释的字符 。以下是元字符列表:
[]。 ^ $ * +? {}()\ |
[]
-方括号
方括号指定您要匹配的一组字符 。
Expression | String | Matched? |
---|---|---|
[abc] |
a |
1 match |
ac |
2 matches | |
Hey Jude |
No match | |
abc de ca |
5 matches |
在这里,如果您要匹配的字符串包含a
, b
或c
中的任何a
,则[abc]
将匹配。
您还可以使用-
在方括号内指定字符范围。
[ae]
与[abcde]
相同。
[1-4]
与[1234]
相同。
[0-39]
与[01239]
相同。
您可以通过在方括号的开头使用插入号^
符号来补充(反转) 字符集。
[^abc]
表示除a
或b
或c
之外a
任何字符 。
[^0-9]
表示任何非数字字符。
.
-期间
句点匹配任何单个字符 (换行符'\n'
除外)。
Expression | String | Matched? |
---|---|---|
.. |
a |
No match |
ac |
1 match | |
acd |
1 match | |
acde |
2 matches (contains 4 characters) |
^
-插入符号
插入符号^
用于检查字符串是否以某个特定字符开头 。
Expression | String | Matched? |
---|---|---|
^a |
a |
1 match |
abc |
1 match | |
bac |
No match | |
^ab |
abc |
1 match |
acb |
No match (starts with a but not followed by b ) |
$
-美元
美元符号$
用于检查字符串是否以特定字符结尾 。
Expression | String | Matched? |
---|---|---|
a$ |
a |
1 match |
formula |
1 match | |
cab |
No match |
*
-星
星号*
匹配零个或多个剩余的模式。
Expression | String | Matched? |
---|---|---|
ma*n |
mn |
1 match |
man |
1 match | |
mann |
1 match | |
main |
No match (a is not followed by n ) |
|
woman |
1 match |
+
-加
加号+
匹配出现在其上的一个或多个模式。
Expression | String | Matched? |
---|---|---|
ma+n |
mn |
No match (no a character) |
man |
1 match | |
mann |
1 match | |
main |
No match (a is not followed by n ) |
|
woman |
1 match |
?
-问号
问号符号?
匹配零或一出现的模式。
Expression | String | Matched? |
---|---|---|
ma?n |
mn |
1 match |
man |
1 match | |
mann |
No match (more than one a character) |
|
main |
No match (a is not followed by n ) |
|
woman |
1 match |
{}
-大括号
考虑以下代码: {n,m}
。这意味着至少要保留n
样式,最多m
重复样式。
Expression | String | Matched? |
---|---|---|
a{2,3} |
abc dat |
No match |
abc daat |
1 match (at daat ) |
|
aabc daaat |
2 matches (at aabc and daaat ) |
|
aabc daaaat |
2 matches (at aabc and daaaat ) |
让我们再尝试一个示例。此RegEx [0-9]{2, 4}
匹配至少2位但不超过4位。
Expression | String | Matched? |
---|---|---|
[0-9]{2,4} |
ab123csde |
1 match (match at ab123csde ) |
12 and 345673 |
3 matches (12 , 3456 , 73 ) |
|
1 and 2 |
No match |
|
-交替
竖条|
用于交替( or
运算符)。
Expression | String | Matched? |
---|---|---|
a|b |
cde |
No match |
ade |
1 match (match at ade ) |
|
acdbea |
3 matches (at acdbea ) |
此处, a|b
匹配包含a
或b
任何字符串
()
-组
括号()
用于对子模式进行分组。例如, (a|b|c)xz
匹配任何匹配a
或b
或c
字符串 ,后跟xz
Expression | String | Matched? |
---|---|---|
(a|b|c)xz |
ab xz |
No match |
abxz |
1 match (match at abxz ) |
|
axz cabxz |
2 matches (at axzbc cabxz ) |
\
-反斜杠
反冲\
用于转义包括所有元字符在内的各种字符。例如,
\$a
如果字符串包含$
后跟a
$
则匹配。此处,RegEx引擎不会以特殊方式解释$
。
如果不确定某个字符是否具有特殊含义,可以在其前面加上\
。这样可以确保不对字符进行特殊处理。
特殊序列
特殊序列使常用模式更易于编写。以下是特殊序列的列表:
\A
如果指定的字符位于字符串的开头,则匹配。
Expression | String | Matched? |
---|---|---|
\Athe |
the sun |
Match |
In the sun |
No match |
\b
如果指定字符在单词的开头或结尾,则匹配。
Expression | String | Matched? |
---|---|---|
\bfoo |
football |
Match |
a football |
Match | |
foo\b |
a football |
No match |
the foo |
Match | |
the afoo test |
Match | |
the afootest |
No match |
\B
与\b
相反。如果指定的字符不在单词的开头或结尾,则匹配。
Expression | String | Matched? |
---|---|---|
\Bfoo |
football |
No match |
a football |
No match | |
foo\B |
a football |
Match |
the foo |
No match | |
the afoo test |
No match | |
the afootest |
Match |
\d
匹配任何十进制数字。相当于[0-9]
Expression | String | Matched? |
---|---|---|
\d |
12abc3 |
3 matches (at 12abc3 ) |
JavaScript |
No match |
\D
匹配任何非十进制数字。相当于[^0-9]
Expression | String | Matched? |
---|---|---|
\D |
1ab34"50 |
3 matches (at 1ab34"50 ) |
1345 |
No match |
\s
匹配字符串包含任何空格字符。等效于[ \t\n\r\f\v]
。
Expression | String | Matched? |
---|---|---|
\s |
JavaScript RegEx |
1 match |
JavaScriptRegEx |
No match |
\S
匹配字符串包含任何非空白字符。等效于[^ \t\n\r\f\v]
。
Expression | String | Matched? |
---|---|---|
\S |
a b |
2 matches (at a b ) |
No match |
\w
匹配任何字母数字字符 (数字和字母)。等效于[a-zA-Z0-9_]
。顺便说一下,下划线_
也被认为是字母数字字符。
Expression | String | Matched? |
---|---|---|
\w |
12&": ;c |
3 matches (at 12&": ;c ) |
%"> ! |
No match |
\W
匹配任何非字母数字字符。等效于[^a-zA-Z0-9_]
Expression | String | Matched? |
---|---|---|
\W |
1a2%c |
1 match (at 1a2%c ) |
JavaScript |
No match |
\Z
如果指定的字符位于字符串的末尾,则匹配。
Expression | String | Matched? |
---|---|---|
JavaScript\Z |
I like JavaScript |
1 match |
I like JavaScript Programming |
No match | |
JavaScript is fun |
No match |
提示 :要构建和测试正则表达式,可以使用RegEx测试器工具,例如regex101。该工具不仅可以帮助您创建正则表达式,而且还可以帮助您学习它。
现在,您了解了RegEx的基础知识,让我们讨论如何在JavaScript代码中使用RegEx。
JavaScript正则表达式方法
如上所述,您可以使用RegExp()
或正则表达式字面量在JavaScript中创建RegEx。
const regex1 = /^ab/;
const regex2 = new Regex('/^ab/');
在JavaScript中,可以将正则表达式与RegExp()
方法一起使用; test()
和exec()
。
还有一些字符串方法,可让您传递RegEx作为其参数。它们是: match()
, replace()
, search()
和split()
。
Method | Description |
---|---|
exec() |
Executes a search for a match in a string and returns an array of information. It returns null on a mismatch. |
test() |
Tests for a match in a string and returns true or false. |
match() |
Returns an array containing all the matches. It returns null on a mismatch. |
matchAll() |
Returns an iterator containing all of the matches. |
search() |
Tests for a match in a string and returns the index of the match. It returns -1 if the search fails. |
replace() |
Searches for a match in a string and replaces the matched substring with a replacement substring. |
split() |
Break a string into an array of substrings. |
示例1:正则表达式
let string = 'Find me';
let pattern = /me/;
// search if the pattern is in string variable
let result = string.search(pattern);
console.log(result); // 5
// replace the character with another character
let string1 = 'Find me';
string1.replace(pattern, 'found you'); // Find found you
// splitting strings into array elements
const re = /[\s,]+/;
let result = 'Hello world! '.split(re);
console.log(result); // ["I", "am", "learning", "JavaScript", "RegEx"]
// searching the phone number pattern
let re = /(\d{3})\D(\d{3})-(\d{4})/g;
let result = re.exec('My phone number is: 555 123-4567.');
console.log(result); // ["555 123-4567", "555", "123", "4567"]
正则表达式标志
标志与正则表达式一起使用,这些正则表达式允许各种选项,例如全局搜索,不区分大小写的搜索等。它们可以单独使用,也可以一起使用。
Flags | Description |
---|---|
g |
Performs a global match (find all matches) |
m |
Performs multiline match |
i |
Performs case-insensitive matching |
示例2:正则表达式修饰符
let string = 'Hello hello hello';
// performing a replacement
let result1 = string.replace(/hello/, 'world');
console.log(result1); // Hello world hello
// performing global replacement
let result2 = string.replace(/hello/g, 'world');
console.log(result2); // Hello world world
// performing case-insensitive replacement
let result3 = string.replace(/hello/i, 'world');
console.log(result3); // world hello hello
// performing global case-insensitive replacement
let 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: learningJS@gmail.com
The email is valid.