正则表达式匹配条件但不返回它

时间:2013-05-21 14:51:48

标签: javascript regex

在这里,我试图在正则表达式上找到清楚的东西。 我创建了这个正则表达式:

a.match( /(@|#)(.*?)(\s|$|\:)/g )

它匹配推文中的所有用户和hastags。 问题是他们返回条件(@ |#)和(\ s | $ | \:)

有可能不归还吗?

我正在使用Javascript

var a ='RT @OLMJanssen: Met #FBKGames en @Jmvanhalst volop in voorbereiding: 6 juni seminar kwaliteitsborging van #sportaccommodatie bij regiseerende gemeente'
a.match( /(@|#)(.*?)(\s|$|\:)/g )
//returns ["@OLMJanssen:", "#FBKGames ", "@Jmvanhalst ", "#sportaccommodatie "]

3 个答案:

答案 0 :(得分:4)

怎么样:

a.match(/[@#](\S+)(?:\s|:|$)/g)

<强>解释

The regular expression:

(?-imsx:[@#](\S+)(?:\s|:|$))

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  [@#]                     any character of: '@', '#'
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    \S+                      non-whitespace (all but \n, \r, \t, \f,
                             and " ") (1 or more times (matching the
                             most amount possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  (?:                      group, but do not capture:
----------------------------------------------------------------------
    \s                       whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    :                        ':'
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
----------------------------------------------------------------------
  )                        end of grouping
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

答案 1 :(得分:1)

这应该可以解决问题:/[@#]([^\s$:]+)/g

答案 2 :(得分:0)

拥有你所拥有的东西(即一群人不是一个阶层)

var match, re = /(@|#)(.*?)(\s|$|\:)/g;
while (match = re.exec(a)) {
 alert(match[2]); // match[1] is "#" or "@"
}