2

I've been struggling getting my regex function to work as intended. My goal is to iterate endlessly over a string (until no match is found) and remove all duplicate, adjacent characters. Aside from checking if 2 characters (adjacent of each other) are equal, the regex should only remove the match when one of the pair is uppercase.

e.g. the regex should only remove 'Xx' or 'xX'.

My current regex only removes matches where a lowercase character is followed by any uppercase character.

(.)(([a-z]{0})+[A-Z])

How can I implement looking for the same adjacent character and the pattern of looking for an uppercase character followed by an equal lowercase character?

1
  • 2
    is there a need for regex here? Commented Jul 23, 2019 at 7:29

2 Answers 2

3

You'd either have to list out all possible combinations, eg

aA|Aa|bB|Bb...

Or implement it more programatically, without regex:

let str = 'fooaBbAfoo';
outer:
while (true) {
  for (let i = 0; i < str.length - 1; i++) {
    const thisChar = str[i];
    const nextChar = str[i + 1];
    if (/[a-z]/i.test(thisChar) && thisChar.toUpperCase() === nextChar.toUpperCase() && thisChar !== nextChar) {
      str = str.slice(0, i) + str.slice(i + 2);
      continue outer;
    }
  }
  break;
}
console.log(str);

Sign up to request clarification or add additional context in comments.

Comments

3

Looking for the same adjacent character: /(.)\1/

Looking for an uppercase character followed by an equal lowercase character isn't possible in JavaScript since it doesn't support inline modifiers. If they were regex should be: /(.)(?!\1)(?i:\1)/, so it matches both 'xX' or 'Xx'

Comments

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.