[英]Split string containing newline characters Java
Say I have a following string str
: 说我有以下字符串
str
:
GTM =0.2
Test =100
[DLM]
ABCDEF =5
(yes, it contains newline characters) That I am trying to split with [DLM]
delimiter substring like this: (是的,它包含换行符)我正在尝试使用
[DLM]
分隔符子字符串进行拆分,如下所示:
String[] strArr = str.split("[DLM]");
Why is it that when I do: 为什么当我这样做时:
System.out.print(strArr[0]);
I get this output: GT
我得到以下输出:
GT
and when I do 当我做的时候
System.out.print(strArr[1]);
I get =0.2
我得到
=0.2
Does this make any sense at all? 这一点有意义吗?
str.split("[DLM]");
should be str.split("\\\\[DLM\\\\]");
应该是
str.split("\\\\[DLM\\\\]");
Why? 为什么?
[
and ]
are special characters and String#split
accepts regex. [
和]
是特殊字符 , String#split
接受正则表达式。
A solution that I like more is using Pattern#quote
: 我更喜欢的解决方案是使用
Pattern#quote
:
str.split(Pattern.quote("[DLM]"));
quote
returns a String representation of the given regex. quote
返回给定正则表达式的String表示形式。
Yes, you're giving a regex which says "split with either D, or L, or M". 是的,您给出的正则表达式为“用D或L或M分割”。
You should escape those boys like this: str.split("\\[DLM\\]"); 您应该像这样逃避那些男孩:str.split(“ \\ [DLM \\]”);
It's being split at the first M. 它在第一个M处被拆分。
Escape the brackets 逃脱括号
("\\[DLM\\]")
When you use brackets inside the " ", it reads it as, each character inside of the brackets is a delimiter. 当在“”内使用方括号时,它的读法为,方括号内的每个字符都是一个定界符。 So in your case,
M
was a delimiter 因此,在您的情况下,
M
是分隔符
use 采用
String[] strArr = str.split("\\[DLM]\\");
Instead of 代替
String[] strArr = str.split("[DLM]");
Other wise it will split with either D, or L, or M. 否则,它将与D或L或M分开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.