Julian H. Lam
Julian H. Lam

Reputation: 26124

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

This is what I have so far: /(^|[\s])#\d+/g

My test string is: "#123 it should match this: #1234, but not this: http://example.org/derp#6326 . How about on a new line?\n\n#1284"

When I attempt to match, I get the following matches:

I attempted to change the regular expression by adding ?: to the grouping, and surrounding what I wanted with parenthesis: /(?:^|[\s])(#\d+)/g, however, this did not work, and provided the same matches

How can I match just the # + numbers, without anything before it?

Upvotes: 0

Views: 154

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98881

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

Upvotes: 0

Robin
Robin

Reputation: 9644

Actually you did capture what you wanted, you just need to look at what's inside the capturing group and not at the whole match...

Try

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);
}

You can see what the regex captures clearly here

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173542

A memory capture will do the trick:

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

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

Demo

Upvotes: 1

Related Questions