【问题标题】:linkify words using regex使用正则表达式链接单词
【发布时间】:2014-09-03 14:48:24
【问题描述】:

我正在尝试使用正则表达式链接主题标签,大多数情况下都有效,除非hot. 末尾有一个带点的单词,这应该只链接#hot,但同时#hot.hot 是有效

这是我的正则表达式代码:

var text = "#hot#hot hot #hot #hot.hot #hót #hot_hot #hot, (#hot) #hot. hot";
text.replace(#([^\b#,() ]*)/g, '<a href="/$1">#$1</a>');

输出:

<a href="/hot">#hot</a><a href="/hot">#hot</a> hot <a href="/hot">#hot</a> <a href="/hot.hot">#hot.hot</a> <a href="/hót">#hót</a> <a href="/hot_hot">#hot_hot</a> <a href="/hot">#hot</a>, (<a href="/hot">#hot</a>) <a href="/hot.">#hot.</a> hot

唯一的问题是#hot. 应该只链接#hot 同时#hot.hot 是有效的

【问题讨论】:

  • 我不确定字符类中的“\b”是否真的有任何作用。没有匹配“\b”的字符,因此所有字符都将包含在“[^\b]”中。至少它不处理感叹号之类的东西,如果这是意图的话。

标签: javascript regex hashtag linkify


【解决方案1】:

你的正则表达式很好,但你必须在末尾添加一个单词边界:

#([^\b#,() ]*)\b
              ^-------- Here

Working demo

【讨论】:

  • 谢谢,\b 成功了,如果我用这个我也不需要,(),我可以用/#([^\b# ]*)\b/g
  • @krisrak 太好了,很高兴为您提供帮助。感谢您的打勾
【解决方案2】:

试试这个正则表达式:

/#([^\W]+)/g

\w 仅匹配字母、数字和下划线。所以它的反义词\W 匹配所有 字母、数字或下划线。将 \W 放在否定字符类 ([^\W]) 中,您将获得仍然可以匹配重音字符的所需结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多