1

I want to clean String from unnecessary data, something like:

x, y, z,  g,  h

More precisely, I want delete g and h, becuase before the g and h character, i have 2 "space".

What is the fastest way to accomplish this?

0

3 Answers 3

3

Use String#replaceAll:

String input = "x, y, z,  g,  h";
input = input.replaceAll("\\s{2,}\\w+,?", "");
Sign up to request clarification or add additional context in comments.

1 Comment

@YCF_L That didn't fix the problem, assuming that the OP is concerned even about the last comma.
1

Another variant would be:

String data = "x, y, z,  g,  h";
data = Pattern.compile(",")
              .splitAsStream(data)
              .filter(s -> s.length() - s.trim().length() <= 1)
              .collect(Collectors.joining(","));

if for some reason you still want the last comma included then you can do:

data = Pattern.compile(",")
              .splitAsStream(data)
              .filter(s -> s.length() - s.trim().length() <= 1)
              .collect(Collectors.joining(",", "", ","));

Comments

-2
String str ="x,y,z, g, h;
String newString = str.replaceAll("[^a-zA-Z]","");

o/p:

newString = x,y,x,g,h

Note: if you want to delete g & h character use java split method.

1 Comment

You didn't get the problem : " I want delete g and h, becuase before the g and h character, i have 2 "space"." Not simply remove none letters character in a String. Your "note" is more likely to be correct but how would you do it with a split ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.