我用 JS 编写了一个正则表达式测试器。但是,对于某些正则表达式,我似乎得到了多个匹配项。
例如,如果内容为hello, world
,正则表达式hello.*
给出,据报告匹配 hello, world
。但是,如果正则表达式现在设置为 (hello|goodbye).*
那么报告的匹配项是 hello, world
和hello
,而它应该是 hello, world
仅。
<!DOCTYPE html>
<html>
<head>
<title>Regex tester</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
function resetform() {
document.getElementById("results").innerHTML = "";
}
function escapetags(str) {
return (str.replace('&','&').replace('<', '<').replace('>', '>'));
}
function check() {
if (!document.form1.re.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No regular expression specified</b></p>';
return;
}
if (!document.form1.str.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No content specified</b></p>';
return;
}
var pattern,
modifiers = "";
if (document.form1.nocase.checked) {
modifiers = "i";
}
if (document.form1.global.checked) {
modifiers = modifiers + "g";
}
try {
if (modifiers) {
pattern = new RegExp(document.form1.re.value, modifiers);
} else {
pattern = new RegExp(document.form1.re.value);
}
} catch (excpt) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: Invalid regular expression</b></p>';
return;
}
var matches = pattern.exec(document.form1.str.value);
if (matches == null) {
document.getElementById("results").innerHTML = '<p><b>Regular expression did not match with content<b></p>';
} else {
document.getElementById("results").innerHTML = '<p><b>Regular expression matched with content</b></p><p>Matches:</p>';
for (var index = 0; index < matches.length; index++) {
document.getElementById("results").innerHTML += escapetags(matches[index]) + '<br>';
}
}
}
</script>
<h1>Regex tester</h1>
<form name="form1">
<p>Regex:</p>
<input type="text" name="re" size="65"><br>
<input type="checkbox" name="nocase">Case insensitive
<input type="checkbox" name="global">Global
<p>Content:</p>
<textarea name="str" rows="8" cols="65"></textarea><br><br>
<input type="button" value="Check" onclick="check();">
<input type="button" value="Reset" onclick="reset();resetform();">
</form>
<div id="results"></div>
</body>
</html>
谁能帮我找出代码中的问题吗?
提前致谢。
最佳答案
“(hello|goodbye)。则报告的匹配项为 hello、world 和 hello*”
不,第二个“匹配”只是捕获组的结果(括号之间的内容)。忽略它,或者使该组不捕获:(?:hello|goodbye)
关于javascript - 正则表达式匹配太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16918759/