Home » Java » Regex to remove a character if followed by another character in java-Exceptionshub

Regex to remove a character if followed by another character in java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Working on a regex in java to find words that follow the below rules

Regex Rules:

  1. Word could start with – (optional Prefix)letters could be any of these ‘c”p”y”r”a”u’
  2. Followed by capital T
  3. Followed by number between 0 to 9
  4. (optional Suffix)Followed by lower case letters that doesn’t include
    letters p or y or r or u. Can be one or two letters

Problem:If the above said suffix for the word is a or b or c and followed by a capital N then the regex should ignore that letter and what follows it.Look in test cases for clarification.

Test cases

  1. pT1c – should return the whole word pT1c (since N doesnt follow the c)
  2. cT4bcN2 – should return just cT4b (since c is followed by N ignore those two letters and the rest that follows them)
  3. cT3cN2 – should return cT3(since c is followed by N ignore those 2 letters and the rest that follows them)

So far I have

[cpyrau]*[T][0-9X?][a-oqstv-z]{0,2}([N])?(?(1)(?=[abc]))

Which works for the first test case but for all others it includes the letter before N if it is a or c so I’m getting cT4bc and cT3c for second and third test case.

Any help is appreciated.

How to&Answers:

Does this do what you are after?

\b[cpyrau]*T\d(?:(?![a-c]N)[a-oqstv-z]){0,2}