正则表达匹配:被空间或起点所包围,但不匹配

时间:2014-04-18 15:43:18

标签: javascript regex

这是我到目前为止所做的:/(^|[\s])#\d+/g

我的测试字符串为:"#123 it should match this: #1234, but not this: http://example.org/derp#6326 . How about on a new line?\n\n#1284"

当我尝试匹配时,我得到以下匹配:

  • "#123"
  • " #1234"
  • "\n#1284"(假装那里有一个实际的换行符)

我尝试通过将?:添加到分组来更改正则表达式,并使用括号括起我想要的内容:/(?:^|[\s])(#\d+)/g但是,这不起作用,并提供相同的匹配

如何才能匹配# +号码,之前没有任何内容?

3 个答案:

答案 0 :(得分:1)

实际上你确实抓住了你想要的东西,你只需要看看捕捉小组内部的内容,而不是整场比赛......

尝试

var myString = "#123 it should match this: #1234, but not this: http://example.org/derp#6326 . How about on a new line?\n\n#1284";
var myRegex = /(?:^|\s)(#\d+)/g;
var allMatches = [];
while((result = myRegex.exec(myString)) != null) {
    var match = result[1]; // get the first capturing group of the current match
    allMatches.push(match);
}

您可以清楚地看到正则表达式捕获的内容here

答案 1 :(得分:1)

内存捕获可以解决问题:

var re = /(?:^|[\s])(#\d+)/g;

while (match = re.exec(str)) {
    console.log(match[1]);
}

Demo

答案 2 :(得分:0)

subject= "#1234, but not this: http://example.org/derp#6326";
match = subject.match(/^\s*?#(\d+)/m);
if (match != null) {
    var result =  match[1]
}

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “#” literally «#»
Match the regular expression below and capture its match into backreference number 1 «(\d+)»
   Match a single digit 0..9 «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»