【问题标题】:I need to exclude the specific two-character string `[?` from a regex match search我需要从正则表达式匹配搜索中排除特定的两个字符的字符串 `[?`
【发布时间】:2021-05-08 10:17:20
【问题描述】:

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

/\.(?=\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

标签: javascript regex highlight mark.js


【解决方案1】:

\? 之前将负向回溯(?&lt;!\[) 插入到正则表达式,这意味着正则表达式将采用?,其前面的字符不是[。您可以在否定后向集中添加任何其他字符,以排除 ? 与其他前置字符。

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

另一种解决方案是在? 之前使用普通的否定集[^\[],例如/\.(?=\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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    相关资源
    最近更新 更多