Vitaliy Hayda
Vitaliy Hayda

Reputation: 113

How to ignore the line completely with regex? (lookahead doesn't work)

This is my regex for finding a phone number

(([0-9]{3}[-./ ]{0,1}[0-9]{3}[-./ ]{0,1}[0-9]{4}))|([(][0-9) ]{4,5}[0-9]{3}[-]{0,1}[0-9]{4})

See it in action here - http://regexr.com/3dsbk

My goal is to ignore each result, if its preceding symbol is #

I've tried adding a negative lookahead, like this:

(?!#)(([0-9]{3}[-./ ]{0,1}[0-9]{3}[-./ ]{0,1}[0-9]{4}))|([(][0-9) ]{4,5}[0-9]{3}[-]{0,1}[0-9]{4})

But it doesn't work.

Upvotes: 0

Views: 82

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

The regex itself can't help. You need to use some programming logic around the pattern matching. A usual lookbehind replacement is to use an optional group at the pattern start, and then check if the group matched. If it did, the string before your match exists -> we should discard those matches. Else, get them.

/(#)?[0-9]{3}[-.\/ ]?[0-9]{3}[-.\/ ]?[0-9]{4}|[(][0-9) ]{4,5}[0-9]{3}-?[0-9]{4}/g

See the regex demo that has no value without code below:

var re = /(#)?[0-9]{3}[-.\/ ]?[0-9]{3}[-.\/ ]?[0-9]{4}|[(][0-9) ]{4,5}[0-9]{3}-?[0-9]{4}/g; 
var str = '1012 345 6789\n#1231231231 (only this to be ignored)\nphone 1231231231\n1012.345.6789\n012/345/6789\n555-123-4567    \n+1-(800) 555-2468\n+1-800 555-2468';
var res = [];
while ((m = re.exec(str)) !== null) {
   if (!m[1]) {
      res.push(m[0]);
   }
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";

You might need to adjust your regex to extract whole words only by adding word boundaries \b around the pattern, like /(#)?\b[0-9]{3}[-.\/ ]?[0-9]{3}[-.\/ ]?[0-9]{4}|[(][0-9) ]{4,5}[0-9]{3}-?[0-9]{4}\b/g, but that might require further adjustments.

Upvotes: 1

beatrice
beatrice

Reputation: 4411

([^#](([0-9]{3}[-./ ]{0,1}[0-9]{3}[-./ ]{0,1}[0-9]{4}))|([(][0-9) ]{4,5}[0-9]{3}[-]{0,1}[0-9]{4}))

Upvotes: 1

Related Questions