Home > database >  Javascript regex for matching valid characters without repetition of a particular character
Javascript regex for matching valid characters without repetition of a particular character

Time:03-10

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi;
let s =
    'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href';

let m;
let res = [];

while ((m = rx.exec(s))) {
    res.push(m[1]);
}
console.log(res);
  1. Pattern should start with /MxML/
  2. Keep including acceptable characters [a-z0-9[]@/]
  3. A single = is ok. But == or === are not ok.

Desired output

[
    '/MxML/trades[1]/value',
    '/MxML/trades[type=2]/value',
    '/MxML/stream/pre/reference@href',
];

My current (incorrect) output

[
    '/MxML/trades[1]/value',
    '/MxML/trades[type',
    '/MxML/stream/pre/reference@href',
];

I can think of a lookaround, but can't figure out how to use it here. (?<!\=)\=(?!\=)

I've been going through several other examples on Stackoverflow, but they are about avoiding all character repetition and not about avoiding a particular character(=) repetition in conjunction with other valid characters.

CodePudding user response:

Here is a regex which should be compatible in all browsers:

/(\/MxML\/(?:[a-z0-9\[\]@/]|=(?!=))*)/gi
  • /(\/MxML\/ - your regex
  • (?: - start non-capture group; we need this to implement an "or" operator and not mess up your use of m[1]
    • [a-z0-9\[\]@/] - your regex of whitelisted chars; notice the asterisk was removed
    • | - or
    • =(?!=) - allow for an equal sign not followed by an equal sign
  • )* - close non-capturing group and capture between zero and infinity instances of what's inside
  • )/gi - your regex

let rx = /(\/MxML\/(?:[a-z0-9\[\]@/]|=(?!=))*)/gi;
let s =
    'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href';

let m;
let res = [];

while ((m = rx.exec(s))) {
    res.push(m[1]);
}
console.log(res);

  • Related