由于String.split()使用正则表达式,此片段:
String s = "str?str?argh";
s.split("r?");
Run Code Online (Sandbox Code Playgroud)
...收益率: [, s, t, , ?, s, t, , ?, a, , g, h]
什么是在r?序列上拆分此字符串以使其生成的最优雅的方法[st, st, argh]?
编辑:我知道我可以摆脱这个问题?.问题是我不知道分隔符,我不想通过编写escapeGenericRegex()函数来解决这个问题.
Ste*_*n C 78
仅使用Java SE API的一般解决方案是:
String separator = ...
s.split(Pattern.quote(separator));
Run Code Online (Sandbox Code Playgroud)
该quote方法返回一个正则表达式,该正则表达式将参数字符串作为文字匹配.
小智 10
您可以使用
StringUtils.split("?r")
Run Code Online (Sandbox Code Playgroud)
来自commons-lang.
逃离?:
s.split("r\\?");
Run Code Online (Sandbox Code Playgroud)
这也很完美:
public static List<String> splitNonRegex(String input, String delim)
{
List<String> l = new ArrayList<String>();
int offset = 0;
while (true)
{
int index = input.indexOf(delim, offset);
if (index == -1)
{
l.add(input.substring(offset));
return l;
} else
{
l.add(input.substring(offset, index));
offset = (index + delim.length());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17834 次 |
| 最近记录: |