用于匹配类似Twitter的主题标签的Javascript正则表达式 [英] Javascript regex for matching twitter-like hashtags

查看:84
本文介绍了用于匹配类似Twitter的主题标签的Javascript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想帮助找出用于识别hashtags的JS正则表达式,它们应该匹配以下所有内容:

I'd like some help on figuring out the JS regex to use to identify "hashtags", where they should match all of the following:


  1. 通常的twitter风格主题标签: #foobar

  2. 前面有文字的Hashtags: abc123#xyz456

  3. 其中带有空格的Hashtags,表示为:#[foo bar] (也就是说,[]作为标签的分隔符)

  1. The usual twitter style hashtags: #foobar
  2. Hashtags with text preceding: abc123#xyz456
  3. Hashtags with space in them, which are denoted as: #[foo bar] (that is, the [] serves as delimiter for the hashtag)

对于1和2,我使用了某些东西以下形式:

For 1 and 2, I was using something of the following form:

var all_re =/\S*#\S+/gi;

我似乎无法弄清楚如何将它扩展到3.我不擅长regexps,请帮忙吗?

I can't seem to figure out how to extend it to 3. I'm not good at regexps, some help please?

谢谢!

推荐答案

所以它必须匹配所有非空格字符或(包括) [] 之间的任何字符:

So it has to match either all non-space characters or any characters between (and including) [ and ]:

\S*#(?:\[[^\]]+\]|\S+)

说明:

\S*                # any number of non-white space characters
#                  # matches #
(?:                # start non-capturing group
    \[             # matches [
    [^\]]+         # any character but ], one or more
    \]             # matches ]
    |              # OR
    \S+            # one or more non-white space characters
)                  # end non-capturing group

参考交替否定了角色类

这篇关于用于匹配类似Twitter的主题标签的Javascript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆