Regex匹配:被空格或行首包围,但不匹配

Regex Matching: Surrounded by space or start of line, but not matched

本文关键字:包围 不匹配 行首 匹配 空格 Regex      更新时间:2023-09-26

这就是我目前所拥有的:/(^|['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,但这不起作用,并且提供了相同的匹配

如何只匹配#+数字,而之前没有任何内容?

内存捕获可以完成任务:

var re = /(?:^|['s])(#'d+)/g;
while (match = re.exec(str)) {
    console.log(match[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);
}

您可以在这里清楚地看到regex捕获的内容

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) «+»