Reputation: 371
I have a string from a file that I read and I want to remove contents of that string. An example would be like this: PN ,D2 ,R2 , F ,Di , B ,Ri ,Fi
What I want to do is to remove all the commas and if there is more than one space between each 1 or two characters like R2 , F
I would want to remove the extra space and comma. So far I have been able to remove some other contents in the string but can't seem to be able to remove the commas and extra spaces.
String cleanerLine = reverseLine.replaceAll("PN ,", "");
System.out.print("Solution: " + cleanerLine);
The output is like this:
Solution: D2 ,R2 , F ,Di , B ,Ri ,Fi
Upvotes: 0
Views: 81
Reputation: 477749
The String.replaceAll(String,String)
method takes as **first argument a regular expression. So you could write something like:
String cleanerLine = reverseLine.replaceAll("PN ,","")
.replaceAll(",", "")
.replaceAll(" {2,}"," ");
The " {2,}"
is a regular expression that matches with all "two or more spaces".
When reverseLine
is:
String reverseLine = "PN ,D2 ,R2 , F ,Di , B ,Ri ,Fi";
System.out.println(reverseLine.replaceAll("PN ,","").replaceAll(",", "").replaceAll(" {2,}"," "));
it produces:
D2 R2 F Di B Ri Fi
Upvotes: 2