Search code examples
javastringstringbuilder

Removing unwanted char in the String


I have a string

String seq = "AGAGTTAAGTG+A";

I want to remove all the characters except A,C,G and T. So that string can change into

String newseq ="AGAGTTAAGTGA"

I have tried below code but that didn't really work:

String result = str.replaceAll("[^!+]", "");

I heard StringBuilder method can be used, but I am not sure how I'd use it. Can anyone advise me on how to do this?


Solution

  • You can use the ^ character to negate a group:

    String result = seq.replaceAll("[^ACGT]", "");