[英]replacing several different characters in a string java
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. 例如:
PN ,D2 ,R2 , F ,Di , B ,Ri ,Fi
我想要做的是删除所有逗号,如果像R2 , F
这样的每1个或2个字符之间有一个以上的空格R2 , F
我想删除多余的空格和逗号。 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
输出是这样的:
Solution: D2 ,R2 , F ,Di , B ,Ri ,Fi
The String.replaceAll(String,String)
method takes as **first argument a regular expression . String.replaceAll(String,String)
方法将正则表达式作为第一个参数。 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 ". " {2,}"
是与所有“ 两个或多个空格 ”匹配的正则表达式。
When reverseLine
is: 当
reverseLine
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.