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开发者_C百科 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
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
,
精彩评论