javascript中的正则表达式回溯

regex lookbehind in javascript

本文关键字:回溯 正则表达式 javascript      更新时间:2023-09-26

我正在尝试匹配文本中的一些单词

工作示例(我想要的)regex101:

regex = /(?<![a-z])word/g
text = word 1word !word aword

只匹配前三个单词,这是我想要实现的。但是,后面的外观在javascript中不起作用:(

所以现在我尝试这个regex101:

regex = /('b|'B)word/g
text = word 1word !word aword

,但所有单词都将匹配,并且它们的前面不能有其他字母,只能有整数或特殊字符。如果我只使用较小的"'b",则1字不匹配;如果我只使用"'b",则!字不匹配

编辑

输出应为["word","word","word"]

和1 !不能包含在匹配中也不能在另一个组中,这是因为我想用javascript .replace(regex,function(match){}),它不应该在1和!

上循环

代码用于

    for(var i = 0; i < elements.length; i++){
    text = elements[i].innerHTML;
    textnew = text.replace(regexp,function(match){
        matched = getCrosslink(match)[0];
        return "<a href='"+matched.url+"'>"+match+"</a>";
    });
    elements[i].innerHTML = textnew;
}

捕捉前导字符

如果没有看到更多的输出示例,很难确切地知道您想要什么,但是如何查找以边界开头或以非字母开头的呢?例如:
('bword|[^a-zA-Z]word)

输出:['word', '1word', '!word']

下面是一个工作示例


仅捕获"word"

如果您只想捕获"word"部分,您可以使用以下命令获取第二个捕获组:

('b|[^a-zA-Z])(word)

输出:['word', 'word', 'word']

下面是一个工作示例


与替代()

您可以在定义替换值时使用特定的捕获组,因此这将为您工作(其中"new"是您想要使用的单词):

var regex = /('b|[^a-zA-Z])(word)/g;
var text = "word 1word !word aword";
text = text.replace(regex, "$1" + "new");

输出:"new 1new !new aword"

下面是一个工作示例

如果您在replace中使用专用函数,请尝试:

textnew = text.replace(regexp,function (allMatch, match1, match2){
    matched = getCrosslink(match2)[0];
    return "<a href='"+matched.url+"'>"+match2+"</a>";
});

下面是一个工作示例

您可以使用以下regex

([^a-zA-Z]|'b)(word)

直接使用replace作为

var str = "word 1word !word aword";
str.replace(/([^a-zA-Z]|'b)(word)/g,"$1"+"<a>$2</a>");
正则表达式