使用Regex排除标签中的尾随点

Exclude a trailing dot in hashtag using Regex

本文关键字:Regex 排除 标签 使用      更新时间:2023-09-26

我正在尝试将文本中的标签转换为一些<a href="/tag/...">...</a>链接。

我尝试使用的代码是

text.replace(/#([^#'s@]+)/ig, "<a href='/tag/$1'>#$1</a>")

但当测试文本如下时,它失败了

blah blah #example.

尾随点将匹配,结果链接将变为

blah blah <a href='/tag/example.'>#example.</a>

这不是我想要的结果。是否有任何方法可以排除尾随点,但将点保持在每个哈希标签之间?类似blah blah #keep.the.dot.in.between #example2

这是一把小提琴http://jsfiddle.net/quvhfky8/

text.replace(/#([^#'s@]*[^.'s])+/ig, "<a href='/tag/$1'>#$1</a>")

以上内容应该能满足您的需求。

它将忽略"#hello"上的尾随句号,但捕获"#hello.whatever"它还将排除任何最后一个点,例如"#hello.whatever."将捕获,就好像最后一个点将不在"#hello.whatever"一样

这里有一个链接,可以向您展示它的实际操作:http://regexr.com/3ao8lRegexr是一个测试模式的好网站!

如果这不是你想要的,请发表评论,我会尽力照顾你。

您可以使用:

'blah blah #this.is.example.'.replace(/#([^#'s@]*[^.])/g, "<a href='/tag/$1'>#$1</a>")
"blah blah <a href='/tag/this.is.an.exampl'>#this.is.example</a>."

我认为您可以使用#([^#'s@]+)(?=$|'b) regex来利用word boundary锚点。此外,我更喜欢使用"双引号(我只是更喜欢这种风格):

var re = /#([^#'s@]+)(?=$|'b)/g; 
var str = 'blah blah #example.  blah blah #keep.the.dot.in.between #example2';
var subst = '<a href="/tag/$1">#$1</a>';
var result = str.replace(re, subst);
document.getElementById("res").innerHTML = result;
<div id="res"/>