无法替换字符串

时间:2013-11-30 04:05:20

标签: java string

我正在直接从控制台读取iptables日志输出,我需要稍微清除一下结果。

目前我正在:

SRC=192.168.1.1 PROTO=UDP DPT=12638
SRC=192.168.1.1 PROTO=UDP DPT=5636
SRC=192.168.1.1 PROTO=UDP DPT=8861
SRC=192.168.1.1 PROTO=UDP DPT=15114

我正在尝试删除SRC =,PROTO =和DPT = ...

String results=a.toString();

results.replace("SRC="," ");
results.replace("PROTO="," ");
results.replace("DF TYPE=3"," ");

tv=(TextView)findViewById(R.id.tv1);
tv.setText("results:\n"+results);

当然没有任何东西被删除:D

3 个答案:

答案 0 :(得分:1)

以这种方式使用正则表达式

results=results.replaceAll("(SRC|PROTO|DF TYPE)=", " ");

这将在一行中用“”(空格)替换src或proto或df类型。无需编写替换 3次

答案 1 :(得分:-1)

尝试这种方式:

results = results.replaceAll("SRC="," ");
results = results.replaceAll("PROTO="," ");

和@Sotirios Delimanolis是对的。

答案 2 :(得分:-1)

改变这个:

results.replace("SRC="," ");
results.replace("PROTO="," ");
results.replace("DF TYPE=3"," ");

对此:

results = results.replace("SRC="," ");
results = results.replace("PROTO="," ");
results = results.replace("DF TYPE=3"," ");

但是你说你想摆脱它们,所以我猜你不想要一个空白区域,我猜你们什么都不想要。您还说“我正在尝试删除SRC =,PROTO =和DPT = ...”,那么为什么要这样做:replace("DF TYPE=3","")?我建议这个:

results = results.replace("SRC=","");
results = results.replace("PROTO=","");
results = results.replace("DPT=","");

或者这个(归功于Jason Sperske):

results = results.replaceAll("(SRC|PROTO|DPT)=", " ");

.replace(String, String)将返回替换的String,但不会更改当前现有String的值。正如Sotirios Delimanolis所说,字符串是不可变的。