JavaScript在正则表达式中标记最后一次出现

JavaScript marking last occurrence in regular expression

本文关键字:最后一次 正则表达式 JavaScript      更新时间:2023-09-26

我有以下任务要做:写一个有两个文本区域T1和T2的网页。用户在文本区域T1中输入一个字符串来表示正则表达式。然后,用户在文本区域T2中输入一些文本。您的代码应该输出T2的文本,其中高亮显示的元素对应于T1的正则表达式的匹配项。我的任务的附加要求是只匹配最后一个出现。

这是我目前为止写的:

<script>
var str = "This is really cooly";
str = str.replace(/'ly(?=[^'ly]*)$/, "BA");
document.write(str + '<br>');
</script>

但这只匹配最后一个单词以"ly"结尾的情况。

我成功地在表单中做到了这一点,但只针对第一次出现。

<html>
<body>
<p id="demo">Click the button to display the matches.</p>
<form name="My_form" id="My_form">
T1:<input type="text" name="T1" id="T1" size=200>
<br>
T2:<input type="text" name="T2" id="T2" size=200>
</form>
<br>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
  var regex = document.My_form.T1.value;
  var n = regex.match(document.My_form.T2.value);
  var result = regex.replace(n, '<b>$&</b>');
  document.getElementById('demo').innerHTML = result;
}
</script>
</body>
</html>

我不知道如何将用户输入转换为e模式以搜索到正则表达式(我不确定这是否可能)。这让我一个多星期都在绞尽脑汁,而我只有不到24小时的时间来完成它。

非常感谢您的帮助。这是有帮助的,但我不确定它是否涵盖了任务的要求,因为我认为它是一个字符串操作算法。

我刚刚完成了我的任务。我的错误是我试图匹配replace()函数中的表达式。问题是表达式实际上应该直接用RegExp对象创建。

这是我的完整代码:

var regex = new RegExp(document.My_form.T2.value+"(?!.*"+document.My_form.T2.value+")", 'g');
var result = document.My_form.T1.value.replace(regex, '<b><font color="blue">$&</font></b>');
document.getElementById("display").innerHTML=result;

再次感谢您的帮助

用户在文本区域T1中输入一个字符串来表示正则表达式。

如果它确实是一个正则表达式,那么您可能想要尝试捕获当您将正则表达式提供给RegExp构造函数时抛出的异常,以防输入无效。我假设输入的正则表达式没有分隔符和标志。

如果要求你在T2中找到T1,那么你可以使用String.indexOf函数来搜索字符串。

您的代码应该输出T2的文本,其中高亮显示的元素对应于T1的正则表达式的匹配。我的任务的附加要求是只匹配最后一个出现。

要突出显示文本,您需要匹配项的索引。

RegExp实例的构造中,将g(全局)标志传递给构造函数。然后,您可以在循环中使用RegExp.exec,根据正则表达式查找索引和所有匹配的长度。

var regex,
    arr,
    output;
try {
    regex = new RegExp(inputT1, 'g');
} catch (e) {
    console.log("Invalid regular expression");
}
while ((arr = regex.exec(inputT2)) !== null) {
    // Starting index of the match
    var startIndex = arr.index;
    // Ending index of the match
    var endIndex = arr.index + arr[0].length;
    // If you only want to highlight the last occurrence only, it can be done by
    // storing the result of previous call to RegExp.exec, then process it
    // outside the loop.
    // Hope you can figure out the rest
    // Advance the lastIndex if an empty string is matched
    if (arr[0].length == 0) {
        re.lastIndex += 1;
    }
}