我有一个看起来像这样的字符串。
String str="some data some data some data some data some data some data
some data some data some data some data some data some data some data
some data some data some data some data some data some data
some data some data some data some data some data
some data some data some data some data some data
YLOG^2Fri Nov 08 00:58:59 PST 2013^^^^^^^^^^^^^^^^^^^^^latency in nano time : 264414262^
YLOG^2Fri Nov 08 00:58:59 PST 2013^^^^ XML after modification :<site name="some data ">
some data some data some data some data some data some data some data
some data some data some data some data some data some data
some data some data some data some data some data
some data some data some data some data some data some data some data some data some data some data some data some data
some data some data some data some data some data some data
some data some data some data some data some data
some data some data some data some data some data "
我想将此字符串拆分为部分。基本上我需要
之后的部分纳秒时间的^ p ^^^^^^^延迟:
那将是:
264414262^
YLOG^2Fri Nov 08 00:58:59 PST 2013^^^^ XML after modification :<site name="some data ">
some data some data some data some data some data some data some data
some data some data some data some data some data some data
some data some data some data some data some data
some data some data some data some data some data some data some data some data some data some data some data some data
some data some data some data some data some data some data
some data some data some data some data some data
some data some data some data some data some data
我尝试了什么:
String[] splited = str.split("^^^^^latency in nano");
Sysout(splitted);
但这对我没有用。 任何帮助将不胜感激。
答案 0 :(得分:2)
我需要......之后的部分。
这让我选择indexOf
而不是split
public String getSub(String orig){
String delim = "^^^^^latency in nano";
int idx = orig.indexOf(delim);
if(idx != -1){
return orig.substring(idx + delim.length());
}
return orig; // delim not found.
}
答案 1 :(得分:2)
拆分不起作用的原因是因为'^'是正则表达式中的元字符。 http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
如果你真的想使用split,你应该转义'^'字符
String[] splitted = str.split("\\^\\^\\^\\^\\^latency in nano");
System.out.println(splitted[1];
在这种情况下,最好只使用indexOf
答案 2 :(得分:1)
分裂后,只需获取第二个元素splitted[1]
。在你拆分之后,这应该给你一切。
存在一些安全问题,但如果输入在形式上始终保持不变,它应该有效。
一些建议:
确保输入包含您要拆分的字符串,并且后面有内容。
-OR -
在获得第二个元素之前,确保splitted
的长度至少为两个。
此外,Sysout(splitted)
中的输出可能不正确的原因是由于数组的默认toString()
。打印数组时应该遵循this。
答案 3 :(得分:1)
如果您的“分隔符”不变,则可以substring
原始String
,indexOf
分隔符+其长度。
下面非常难看的例子:
String s = "blah^^^^^^^latency in nano time : baz";
System.out.println(
s.substring(
s.indexOf("^^^^^^^latency in nano time : ") + "^^^^^^^latency in nano time : ".length()
)
);
输出:
baz
注意:
以任何方式分割您的String
。它只返回你的“分隔符”之后的内容。
还要注意错误:
String
中,则代码将返回原始String
的子字符串,从-1
+您的分隔符长度开始-1
+您的分隔符长度大于String
长度,代码将在运行时抛出StringIndexOutOfBoundsException