为什么String.split(" $")不起作用? [英] Why String.split("$") doesn't work?
问题描述
我有三个部分字符串,每个部分由 $
符号分隔符号
例如,
I have three part string with each part seperated by $
symbol
For example,
String s = "abc$efg$xyz";
现在当我使用拆分
方法拆分它时像这样:
Now when I split it using split
method like this:
String values[] = s.split("$");
它 values
数组包含整个字符串为单个元素。
It values
array contains that entire string as a single element.
但是当我使用它时:
String values[]=s.split("\\$");
它完全符合我想要的含义
现在 values
数组包含 abc
, efg
和 xyz
分别在索引0,1和2上。
It perfectly works what I wanted meaning
now the values
array contains abc
,efg
and xyz
on index 0,1 and 2 respectively.
我想知道为什么第一个拆分
没有当我使用分割
单个空格
时使用类似的拆分
);
I was wondering why that first split
didn't work as I used similar split
when splitting on a single white space
using split(" ");
推荐答案
因为字符 $
是正则表达式中用于标记行尾的保留标记。这就是为什么你必须使用 \\
逃避它。
Because the character $
is a reserved token used in regular expressions to mark the end of a line. That's why you have to escape it using \\
.
这篇关于为什么String.split(" $")不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!