正则表达式是形成搜索模式的字符序列。
搜索模式可用于文本搜索和文本替换操作。
正则表达式是形成一个字符的序列搜索模式。
当您在文本中搜索数据时,可以使用此搜索模式来描述您要搜索的内容。
正则表达式可以是单个字符,也可以是更复杂的模式。
正则表达式可用于执行所有类型的操作文本搜索和文本替换运营。
/
pattern/
modifiers;
/91xjr/i;
示例解释:
/91xjr/i是一个正则表达式。
91xjr是一个模式(用于搜索)。
我是一个修饰符(将搜索修改为不区分大小写)。
在 JavaScript 中,正则表达式经常与两者一起使用字符串方法:search()
和replace()
。
这个search()
方法使用表达式来搜索匹配项,并返回匹配项的位置。
这个replace()
方法返回一个修改后的字符串,其中模式被替换。
这个search()
方法在字符串中搜索指定值并返回匹配的位置:
使用字符串在字符串中搜索"W3schools":
let text = "Visit 91xjr!";
let n = text.search("91xjr");
结果为n将:
6
使用正则表达式对字符串中的 "91xjr" 进行不区分大小写的搜索:
let text = "Visit 91xjr";
let n = text.search(/91xjr/i);
结果为n将:
6
这个replace()
方法将指定值替换为字符串中的另一个值:
let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "91xjr");
亲自试一试 »
使用不区分大小写的正则表达式将字符串中的 Microsoft 替换为 91xjr:
let text = "Visit Microsoft!";
let result = text.replace(/microsoft/i, "91xjr");
结果为资源将:
Visit 91xjr!
正则表达式参数(而不是字符串参数)可以在上述方法中使用。
正则表达式可以使您的搜索更加强大(例如不区分大小写)。
修饰符可用于执行不区分大小写的更全局搜索:
Modifier | Description | 尝试一下 |
---|---|---|
i | Perform case-insensitive matching | 尝试一下 » |
g | Perform a global match (find all matches rather than stopping after the first match) | 尝试一下 » |
m | Perform multiline matching | 尝试一下 » |
括号用于查找字符范围:
Expression | Description | 尝试一下 |
---|---|---|
[abc] | Find any of the characters between the brackets | 尝试一下 » |
[0-9] | Find any of the digits between the brackets | 尝试一下 » |
(x|y) | Find any of the alternatives separated with | | 尝试一下 » |
元字符是具有特殊含义的字符:
Metacharacter | Description | 尝试一下 |
---|---|---|
\d | Find a digit | 尝试一下 » |
\s | Find a whitespace character | 尝试一下 » |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b | 尝试一下 » 尝试一下 » |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx | 尝试一下 » |
量词定义数量:
Quantifier | Description | 尝试一下 |
---|---|---|
n+ | Matches any string that contains at least one n | 尝试一下 » |
n* | Matches any string that contains zero or more occurrences of n | 尝试一下 » |
n? | Matches any string that contains zero or one occurrences of n | 尝试一下 » |
在 JavaScript 中,RegExp 对象是具有预定义属性和方法的正则表达式对象。
这个test()
method 是一个RegExp 表达式方法。
它在字符串中搜索模式,并根据结果返回 true 或 false。
以下示例在字符串中搜索字符 "e":
const pattern = /e/;
pattern.test("The best things in life are free!");
由于字符串中有"e",因此上面代码的输出将是:
true
您不必先将正则表达式放入变量中。上面的两行可以缩短为一行:
/e/.test("The best things in life are free!");
这个exec()
method 是一个RegExp 表达式方法。
它在字符串中搜索指定模式,并将找到的文本作为对象返回。
如果未找到匹配项,则返回空值(无效的)目的。
以下示例在字符串中搜索字符 "e":
如需完整参考,请访问我们的完整的 JavaScript 正则表达式参考。
该参考包含所有 RegExp 属性和方法的描述和示例。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!