0

Let's say I wanna match the letters E, Q and W. However, I don't want them matched if they're found in a certain string of characters, for instance, HELLO.

LKNSDG8E94GO98SGIOWNGOUH09PIHELLOBN0D98HREINBMUE
       ^          ^          ^           ^     ^
       yes        yes        NO          yes   yes
johnRivs
  • 135
  • 2
  • 4
  • 19
  • Perhaps you could replace out said string with a placeholder like `{string}` and then find all instances of the characters, and put it back (if necessary). – Quill Dec 15 '15 at 19:56

1 Answers1

3

There's a nifty regex trick you can use for this. Here's some code in JavaScript, but it can be adapted to any language:

var str = 'LKNSDG8E94GO98SGIOWNGOUH09PIHELLOBN0D98HREINBMUE',
    rgx = /HELLO|([EQW])/g,
    match;

while ((match = rgx.exec(str)) != null) {
    if (match[1]) output(match[1] + '\n');
}

function output(x) { document.getElementById('out').textContent += x; }
<pre id='out'></pre>

Basically, you match on HELLO|([EQW]). Since regex is inherently greedly, if it comes across a HELLO, it'll immediately match that, thereby skipping the E inside of it.

Then you can just check the capture group. If there's something in that capture group, we know it's something we want. Otherwise, it must have been part of the HELLO, so we ignore it.

tckmn
  • 57,719
  • 27
  • 114
  • 156