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

时间:2013-05-26 02:30:26

标签: javascript regex last-occurrence

我有以下任务要做: 编写一个包含两个文本区域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>

我不知道如何将用户输入转换为电子模式以搜索到正则表达式(我不确定这是否可能。这让我的大脑燃烧了一个多星期而且我的电脑少于24几个小时来完成这个。

2 个答案:

答案 0 :(得分:0)

  

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

如果它确实是正则表达式,那么您可能希望尝试捕获在将正则表达式提供给RegExp constructor时抛出的异常,以防输入无效。我假设在没有分隔符和标志的情况下输入正则表达式。

如果要求实际上要求您在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;
    }
}

答案 1 :(得分:0)

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

我设法完成了我的任务。我的错误是我试图匹配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;

再次感谢您的帮助:)