Reputation: 1130
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
Reputation: 455282
You can use the replaceAll
method as:
input = input.replaceAll("[^=,\\da-zA-Z\\s]|(?<!,)\\s","");
The regex used is: [^=,\\da-zA-Z\\s]|(?<!,)\\s
which means:
=
,
,
or a any digit or any letter or
any non-space with ""
, effectively
deleting it.,
Upvotes: 7