java 如何拆分字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3034757/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:02:40  来源:igfitidea点击:

How to split a String array?

javaregexarraysstringsplit

提问by James Raitsev

Intention is to take a current line (String that contains commas), replace white space with "" (Trim space) and finally store split String elements into the array.

意图是取当前行(包含逗号的字符串),用“”(修剪空格)替换空格,最后将拆分的字符串元素存储到数组中。

Why does not this work?

为什么这不起作用?

String[] textLine = currentInputLine.replace("\s", "").split(",");

采纳答案by Paul Tomblin

I think you want replaceAll rather than replace.

我认为你想要 replaceAll 而不是 replace。

And replaceAll("\\s","")will remove all spaces, not just the redundant ones. If that's not what you want, you should try replaceAll("\\s+","\\s")or something like that.

replaceAll("\\s","")会删除所有空格,不只是多余的。如果这不是你想要的,你应该尝试replaceAll("\\s+","\\s")或类似的东西。

回答by polygenelubricants

On regex vs non-regex methods

关于正则表达式与非正则表达式方法

The Stringclass has the following methods:

String班有以下方法:

So here we see the immediate cause of your problem: you're using a regex pattern in a non-regex method. Instead of replace, you want to use replaceAll.

所以在这里我们看到了您问题的直接原因:您在非正则表达式方法中使用了正则表达式模式。取而代之的是replace,您想使用replaceAll.

Other common pitfalls include:

其他常见的陷阱包括:

  • split(".")(when a literal period is meant)
  • matches("pattern")is a whole-string match!
    • There's no contains("pattern"); use matches(".*pattern.*")instead
  • split(".")(当一个字面意思时)
  • matches("pattern")是一个完整的字符串匹配!
    • 没有contains("pattern"); 使用matches(".*pattern.*")替代


On Guava's Splitter

在番石榴的 Splitter

Depending on your need, String.replaceAlland splitcombo may do the job adequately. A more specialized tool for this purpose, however, is Splitterfrom Guava.

根据您的需求,String.replaceAllsplit组合可以充分地完成这项工作。然而,用于此目的的更专业的工具Splitter来自 Guava。

Here's an example to show the difference:

这是一个显示差异的示例:

public static void main(String[] args) {
    String text = "  one, two, , five (three sir!) ";

    dump(text.replaceAll("\s", "").split(","));
    // prints "[one] [two] [] [five(threesir!)] "

    dump(Splitter.on(",").trimResults().omitEmptyStrings().split(text));
    // prints "[one] [two] [five (three sir!)] "
}

static void dump(String... ss) {
    dump(Arrays.asList(ss));
}
static void dump(Iterable<String> ss) {
    for (String s : ss) {
        System.out.printf("[%s] ", s);
    }
    System.out.println();       
}

Note that String.splitcan not omit empty strings in the beginning/middle of the returned array. It can omit trailingempty strings only. Also note that replaceAllmay "trim" spaces excessively. You canmake the regex more complicated, so that it only trims around the delimiter, but the Splittersolution is definitely more readable and simpler to use.

请注意,String.split不能在返回数组的开头/中间省略空字符串。它只能省略尾随空字符串。另请注意,replaceAll可能会过度“修剪”空格。您可以使正则表达式更复杂,以便它只修剪分隔符,但该Splitter解决方案绝对更具可读性和更易于使用。

Guava also has (among many other wonderful things) a very convenient Joiner.

Guava 还具有(在许多其他美妙的事物中)一个非常方便的Joiner.

System.out.println(
    Joiner.on("... ").skipNulls().join("Oh", "My", null, "God")
);
// prints "Oh... My... God"

回答by user85421

What you wrote does not match the code:

你写的与代码不符:

Intention is to take a current line which contains commas, store trimmed values of all space and store the line into the array.

意图是获取包含逗号的当前行,存储所有空间的修剪值并将该行存储到数组中。

It seams, by the code, that you want all spaces removed and split the resulting string at the commas (not described). That can be done as Paul Tomblin suggested.

根据代码,您希望删除所有空格并将结果字符串拆分为逗号(未描述)。这可以按照 Paul Tomblin 的建议进行。

String[] currentLineArray = currentInputLine.replaceAll("\s", "").split(",");

If you want to split at the commas and remove leading and trailing spaces (trim) from the resulting parts, use:

如果要在逗号处拆分并从结果部分中删除前导和尾随空格(修剪),请使用:

String[] currentLineArray = currentInputLine.trim().split("\s*,\s*");

(trim()is needed to remove leading spaces of first partand trailing space from last part)

trim()需要删除第一部分的前导空格和最后一部分的尾随空格)

回答by Jagat

If you need to perform this operation repeatedly, I'd suggest using java.util.regex.Patternand java.util.regex.Matcherinstead.

如果您需要重复执行此操作,我建议您使用java.util.regex.Patternandjava.util.regex.Matcher代替。

final Pattern pattern = Pattern.compile( regex);
for(String inp: inps) {
    final Matcher matcher = pattern.matcher( inpString);
    return matcher.replaceAll( replacementString); 
}

Compiling a regex is a costly operation and using String's replaceAll repeatedly is not recommended, since each invocation involves compilation of regex followed by replacement.

编译正则表达式是一项代价高昂的操作,不建议重复使用 String 的 replaceAll,因为每次调用都涉及编译正则表达式,然后进行替换。