我需要从正则表达式匹配搜索中排除特定的两字符字符串 `[?`

问题描述

我正在使用这个正则表达式字符串来查找周围有空格或不是小数部分的所有句点、感叹号和问号:

/\.(?=\s|$)|\?(?=\s|$)|\!(?=\s|$)/g

我正在使用 mark.js 来突出显示这个 RegEx 字符串。如何修改此字符串(或使用另一个字符串),使其不会突出显示紧跟括号后的问号,或 [?

这是我的代码

function Highlight() {
var instance = new Mark(document.getElementById("example"));

instance.unmark();
instance.markRegExp(/\.(?=\s|$)|\?(?=\s|$)|\!(?=\s|$)/g);

}

window.onload = Highlight();
mark {
    background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div id="example">
<p>This is an example paragraph. I would like all the periods to be highlighted. Woohoo! This works very well! Yay! Alright,onto question marks. This is demo2. [? flagged ?] 5.5 is a number. 0.3374 is another number. Does this work?</p>
</div>

mark.js 也有一个 unmark() 方法来取消标记,但我不知道如何将 RegEx 与 unmark() 一起使用。非常感谢帮助。

解决方法

否定lookbehind (?<!\[)\? 之前插入到regex,这意味着regex 将采用前一个字符不是?[。您可以在否定后视集内添加任何其他字符以排除 ? 与其他前面的字符。

警告:并非所有浏览器都支持此功能。

替代解决方案是在 [^\[] 之前使用普通的否定集 ?,像这样 /\.(?=\s|$)|[^\[]\?(?=\s|$)|\!(?=\s|$)/g。但是这个正则表达式也会选择前面的字符。您必须在代码中处理它。

function Highlight() {
var instance = new Mark(document.getElementById("example"));

instance.unmark();
instance.markRegExp(/\.(?=\s|$)|(?<!\[)\?(?=\s|$)|\!(?=\s|$)/g);

}

window.onload = Highlight();
mark {
    background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div id="example">
<p>This is an example paragraph. I would like all the periods to be highlighted. Woohoo! This works very well! Yay! Alright,onto question marks. This is demo2. [? flagged ?] 5.5 is a number. 0.3374 is another number. Does this work?</p>
</div>