Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to trim characters from start and end of the string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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", "");

>Solution :

  • Find: ^[ab]+|[ab]+$
  • Replace: EMPTY
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading