java String.split() *not* 正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6374050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.split() *not* on regular expression?
提问by Konrad Garus
Since String.split()
works with regular expressions, this snippet:
由于String.split()
使用正则表达式,此代码段:
String s = "str?str?argh";
s.split("r?");
... yields: [, s, t, , ?, s, t, , ?, a, , g, h]
...产量: [, s, t, , ?, s, t, , ?, a, , g, h]
What's the most elegant way to split this String on the r?
sequence so that it produces [st, st, argh]
?
在r?
序列上拆分此 String 以生成的最优雅方法是什么[st, st, argh]
?
EDIT: I know that I can escape the problematic ?
. The trouble is I don't know the delimiter offhand and I don't feel like working this around by writing an escapeGenericRegex()
function.
编辑:我知道我可以摆脱有问题的?
。问题是我不知道分隔符,我不想通过编写escapeGenericRegex()
函数来解决这个问题。
回答by Stephen C
A general solution using just Java SE APIs is:
仅使用 Java SE API 的通用解决方案是:
String separator = ...
s.split(Pattern.quote(separator));
The quote
method returns a regex that will match the argument string as a literal.
该quote
方法返回一个正则表达式,它将作为文字匹配参数字符串。
回答by McPepper
回答by Etienne de Martel
Escape the ?
:
逃脱?
:
s.split("r\?");
回答by Martijn Courteaux
This works perfect as well:
这也很完美:
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());
}
}
}
回答by u689069
String[] strs = str.split(Pattern.quote("r?"));
回答by mindas
Use Guava Splitter:
使用番石榴分配器:
Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed string, regular expression or CharMatcher instance. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixed length.
从输入字符串中提取非重叠子字符串,通常通过识别分隔符序列的外观。此分隔符可以指定为单个字符、固定字符串、正则表达式或 CharMatcher 实例。或者,根本不使用分隔符,拆分器可以提取给定固定长度的相邻子字符串。
回答by Manuel Romeiro
Using directly the Pattern class, is possible to define the expression as LITERAL, and in that case, the expression will be evaluated as is (not regex expression).
直接使用 Pattern 类,可以将表达式定义为 LITERAL,在这种情况下,表达式将按原样计算(不是正则表达式)。
Pattern.compile(<literalExpression>, Pattern.LITERAL).split(<stringToBeSplitted>);
example:
例子:
String[] splittedResult = Pattern.compile("r?", Pattern.LITERAL).split("str?str?argh");
will result:
将导致:
[st, st, argh]
回答by Akash Agrawal
try
尝试
String s = "str?str?argh";
s.split("r\?");