【问题标题】:java split stringjava分割字符串
【发布时间】:2011-11-09 12:07:08
【问题描述】:

在 Java 中,如果我有一个具有这种格式的字符串:

( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]

如何拆分字符串以获得这样的字符串数组?

string1 , string2
string2
string4 , string5 , string6

【问题讨论】:

  • 你想要一个字符串数组还是一个字符串数组?

标签: java regex string split tokenize


【解决方案1】:

试试这个:

    String test = "( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]";

    String[] splits = test.split("\\(\\s*|\\)[^\\(]*\\(?\\s*");

    for (String split : splits) {
        System.out.println(split);
    }

【讨论】:

  • +1 split() 在概念上稍微简单一些,但我会添加一点以匹配右括号之前和左括号之后的任何空格,或者删除匹配所有空格的空格在一起。
【解决方案2】:

你可以使用匹配:

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group(1));
} 

匹配 () 之间的任何内容并将其存储到反向引用 1 中。

解释:

 "\\(" +      // Match the character “(” literally
"(" +       // Match the regular expression below and capture its match into backreference number 1
   "." +       // Match any single character that is not a line break character
      "*?" +      // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
")" +
"\\)"        // Match the character “)” literally

【讨论】:

    【解决方案3】:

    您可能希望在 /\(.+?\)/ 上使用 split - 在 java 中是这样的:

    Pattern p = Pattern.compile("\\(.+?\\)");
    Matcher m = p.matcher(myString);
    ArrayList<String> ar = new ArrayList<String>();
    while (m.find()) {
        ar.add(m.group());
    }
    String[] result = new String[ar.size()];
    result = ar.toArray(result);
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 2011-09-12
      • 2020-03-07
      • 1970-01-01
      • 2011-07-14
      相关资源
      最近更新 更多