JavaScript - RegExp exec 方法
JavaScript RegExp.exec() 方法用于在字符串中搜索由正则表达式定义的指定模式。如果匹配成功,则返回包含匹配文本的 数组;否则,返回 null。
在 JavaScript 中,正则表达式 (RegExp) 是一个描述用于定义搜索模式的字符序列的对象。正则表达式的最佳用途是用于表单验证。当用户通过表单提交数据(例如输入字段)时,您可以应用正则表达式来确保数据符合特定条件。
语法
以下是 JavaScript RegExp.exec() 方法的语法 -
RegExp.exec(str)
参数
此方法接受一个名为"str"的参数,如下所述 -
str - 需要搜索的字符串。
返回值
如果找到匹配项,此方法将返回一个包含匹配文本的数组。否则,它将返回空值。
示例
如果找到匹配项,此方法将返回包含匹配文本的数组。
示例 1
在下面的示例中,我们使用 JavaScript RegExp.exec() 方法在字符串中搜索由字符串 "Tutorials point" 中的正则表达式定义的模式 ('to*', 'g')。
<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('to*', 'g');
const str = "Tutorials point";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>An array with matched text: ", arr);
document.write("<br>The array length: ", arr.length);
</script>
</body>
</html>
输出
上述程序返回一个包含匹配文本的数组。
The string to be searched: Tutorials point The regex: /to*/g An array with matched text: to The array length: 1
示例 2
如果没有找到匹配项,该方法将返回 null。
以下是 JavaScript RegExp.exec() 方法的另一个示例。我们使用此方法在字符串中搜索由正则表达式 "Virat is a damn good batsman" 定义的模式 ('/mn\*', 'g')。
<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('/mn\*', 'g');
const str = "Virat is a damn good batsman";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>An array with matched text: ", arr);
document.write("<br>The array length: ", arr.length);
</script>
</body>
</html>
输出
执行上述程序后,将返回 null。
The string to be searched: Virat is a damn good batsman The regex: /\/mn*/g An array with matched text: null
示例 3
我们可以在 条件 语句中使用此方法的 结果 来检查是否找到匹配项。
<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('\llo*', 'g');
const str = "Hello World";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let result = {};
result = regex.exec(str);
//在条件语句中使用方法结果....
if(result != null){
document.write("<br>The string '" + result[0] + "' found.")
} else {
document.write("<br>Not found...");
}
</script>
</body>
</html>
输出
上述程序执行后,将根据条件返回一个语句 -
The string to be searched: Hello World The regex: /llo*/g The string 'llo' found.

