我在file.txt |a|b|c|d|
中有一行,我想在|
之间提取值(结果a,b,c,d
)
我怎么能这样做?
答案 0 :(得分:0)
来自String[] split(String regex)
围绕给定正则表达式的匹配拆分此字符串。 此方法的作用就像通过调用具有给定表达式和limit参数为零的双参数split方法一样。因此,尾随空字符串不包含在结果数组中。
例如,字符串“boo:and:foo”会产生以下结果:
正则表达式结果
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
使用以下代码:
String[] arr = "|a|b|c|d|".split("\\|");
答案 1 :(得分:0)
管道(|
)是正则表达式语言中的特殊字符(split方法将正则表达式作为参数),因此需要进行转义。
您需要使用类似的内容:String[] str = "|a|b|c|d|".split("\\|");
鉴于此:
String[] str = "|a|b|c|d|".split("\\|");
for(String string : str)
System.out.println(string);
将屈服:
//The first string will be empty, since your string starts with a pipe.
a
b
c
d
答案 2 :(得分:0)
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(new File(
"file.txt"));
BufferedReader br = new BufferedReader(fr);
String st;
StringBuffer sb = new StringBuffer();
st = br.readLine();
if (st != null) {
StringTokenizer strTkn = new StringTokenizer(st, "|");
while (strTkn.hasMoreElements()) {
sb.append(strTkn.nextElement());
}
}
System.out.println(sb);
}