开发者

Filtering a string of unwanted chars in Java

开发者 https://www.devze.com 2023-01-28 16:36 出处:网络
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 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 ,
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号