2

My code reads a line from a file and replaces numbers of length 3 to 18 digits.

The thing is I don't want to match numbers that follow the string DOM: (white space after colon).

For example:

match: tttt 23456789 dkdkd

match: 6783456789 dkdkd DOM:

no match: DOM: 23456789 dkdkd

no match: dhdhd DOM: 23456789 dkdkd

no match: DOM: 2789 dkdkd DOM: 34567896

I have tried using negative look-ahead: .*(?!DOM: )[0-9]{3,18}

But it doesn't work, please help.

1
  • 1
    You are looking for negative look-behind, which JS does not yet have. Commented Feb 14, 2016 at 14:14

2 Answers 2

2

You can't since the lookbehind isn't available in javascript.

The workaround is to use a function as replacement with the replace method:

yourstr = yourstr.replace(/\b(DOM: )?\d{3,18}\b/g, function (m, g) {
    return g ? m : 'what you want'; });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I will do something similar to what you have suggested.
1

A usual approach to mimick a lookbehind where a lookahead is not necessary (and here, a lookahead is not used), is through reversal. You reverse both the input string, the regex pattern where you can thus use a lookahead instead of a lookbehind, and then the results:

function revStr(str) {
    return str.split('').reverse().join('');
}

var s = ["tttt 23456789 dkdkd", "6783456789 dkdkd DOM:",
 "DOM: 23456789 dkdkd", "dhdhd DOM: 23456789 dkdkd", "DOM: 2789 dkdkd DOM: 34567896"];
var rex = /\b[0-9]{3,18}\b(?!\s*:MOD\b)/g;  // Regex for matching reversed numbers 
var results = [];                          // Array for results
s.forEach(function(t) {                    // Test each string
     m = revStr(t).match(rex);             // Collect all matches
     if (m) {                              // If we have a match
         m.forEach(function(h) { 
            results.push(revStr(h));       // Reverse each match value and add
         });
     }
  }
);
document.body.innerHTML = "<pre>" + JSON.stringify(results, 0, 4) + "</pre>";

1 Comment

Thanks for your response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.