简体   繁体   中英

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

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.

是否符合您的要求?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM