Home > Software design >  Regex to trim characters from start and end of the string
Regex to trim characters from start and end of the string

Time:08-03

Given the string

abaaabbacadbadabbbaabab

how would you remove as and bs from both the start and end of the string so that we are only left with

cadbad

?

There are three conditions, though:

  1. As and Bs after "c" and before the last "d" must not be removed.
  2. As and Bs at the start and the end of the string can cum in any order or any quantity. So, regex should work the same if string starts with abba, or bbaa, or abababaa or whatever combination od theese letters. The same applies for the string end.
  3. Cs and Ds are just an example. Regex should work for any other letter as long as it is not a or b.

So, in essence, here is what regex should do: Remove every a and b until first letter which is not a or b is encountered. Stop removing. Then again, from behind, remove every a and b until first letter which is not a or b is encountered from behind. Stop removing.

I can not figure this out. I can get regex to remove the fixed length of letters what is not ok since length of as and bs on both start and end sides is not fixed. I can get it to remove all as and bs, what is not ok either because letters a and b inside the "good part" of the string (which is after the first occurrence of any other letter and before [inclusive] the last occurrence) should not be removed. Also, I can get it to remove a substring, but that is also not what I need.

How would you do this with regex?

I do it in Java, if that matters, but, I did not put the Java tag because anyone can answer this. I just need the regex part.

The Java code:

"abaaabbacadbadabbbaabab".replaceAll("regex", "");

CodePudding user response:

  • Find: ^[ab] |[ab] $
  • Replace: EMPTY

CodePudding user response:

The regex below should do the job. It will find the first character that is not a or b. After that any characters can precede until it finds the last character that is not a or b.

[^ab].*[^ab]
  • Related