javascript - 正则表达式仅匹配字符串,而不匹配子字符串

标签 javascript regex string

当单击表中的值时,我将字符串添加到文本区域。必须能够选择和取消选择表中的值,并且它们将从文本区域添加/删除自身。文本区域必须是字符串,并且添加的值不能包含在任何其他字符中。

要添加的值可能包含任何字符,并且可能将其他值之一作为子字符串,以下是一些示例:HOLE 1HOLE 11 孔 17孔 (1)剖切切入离开剪切评论员(史密斯、约翰)(目标)目标

将值附加到文本区域后,再次单击以取消选择它,我将搜索该值并将其删除,如下所示:

var regex = new RegExp("(?![ .,]|^)?(" + mySelectedText + ")(?=[., ]|$)", 'g');
var newDescriptionText = myTextAreaText.replace(regex, '');

正则表达式正确匹配文本的字符串/子字符串,例如然而,cutawayaway 不适用于以括号开头的任何内容,例如(目标)。将单词边界选择器添加到表达式 \b 的开头,将使正则表达式匹配以括号开头的字符串,但不适用于包含相同文本的字符串/子字符串。

有没有办法使用正则表达式来实现这一点?或者其他方法?

这是一个正在运行的 CodePen example从表中添加/删除。

最佳答案

您可以使用字边界 (\b) 来避免取消选择 away 并在列表中包含 cutaway 时出现问题。只需将正则表达式更改为:

regex = new RegExp("(?![ .,]|^)?(\\b" + cellText + "\\b)(?=[., ]|$)", 'g');
                                 ^^^                ^^^

这是我为使其正常工作而更改的代码:

removeFromDescription = function(cell) {
        cell.classList.remove(activeClass);

        // Remove from the active cells arry
        var itemIndex = tempAnnotation.activeCells.indexOf(cell.textContent);
        tempAnnotation.activeCells.splice(itemIndex, 1);

        // Do the regex find/replace
        var annotationBoxText = annotation.value,
        cellText = regexEscape(cell.textContent), // Escape any funky characters from the string

        regex = new RegExp("(^| )" + cellText + "( |$)", 'g');

        var newDescription = annotationBoxText.replace(regex, ' ');

        setAnnotationBoxValue(newDescription);

        console.info('cellText:         ', cellText);
        console.info('annotationBoxText:', annotationBoxText);
        console.info('newDescription:   ', newDescription);
    };

    regexEscape = function(s) {
         return s.replace(/([-\/\\^$*+?.()|[\]{}])/g, `\\$&`);
    };

    setAnnotationBoxValue = function(newValue) {
        annotation.value = newValue;
    };

关于javascript - 正则表达式仅匹配字符串,而不匹配子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469107/

相关文章:

javascript - 自定义 CSS 网格布局

javascript - 突出显示搜索结果字符串大小写问题

c++ - RegExp 查找命令行参数

javascript - 检查句子中是否存在日期字符串 (dd/mm/yyyy)?

javascript - 如何在单元测试中的请求之间更改 $httpBackend when[method] 语句?

javascript - 如何在没有更改属性时添加 CSS 过渡?

javascript - 如何将后端处理作业的状态通知网站前端?

c++ - cstring -> c++ 字符串转换

Javascript转义字符串中的所有单引号

regex - matlab:正则表达式和拆分,并选择一些单元格