Frank
Frank

Reputation: 1130

Filtering a string of unwanted chars in Java

I am looping through hundreds of data entries, most of them valid according to my rules but there are some special characters or unwanted whitespace that must be filtered before the entry is used.

I only want = and , characters to be allowed along with digits and letters. No other special characters. There can be single white spaces but ONLY following a , to separate data.

I am calling a filter method inside a loop:

private String filterText(String textToBeFiltered) {
    String filteredText = null;

    // Remove all chars apart from = and , with whitespace only allowed
    // after the ,

    return filteredText;
}

I am completely new to regex but have been trawling tutorials and would appreciate any ideas.

Thanks!

Frank

Upvotes: 3

Views: 4240

Answers (1)

codaddict
codaddict

Reputation: 455282

You can use the replaceAll method as:

input = input.replaceAll("[^=,\\da-zA-Z\\s]|(?<!,)\\s","");

Ideone Link

The regex used is: [^=,\\da-zA-Z\\s]|(?<!,)\\s which means:

  • replace any character other than =, , or a any digit or any letter or any non-space with "", effectively deleting it.
  • Also delete any whitespace but only if it is not preceded by a ,

Upvotes: 7

Related Questions