【问题标题】:How do i split a String into an array with split and regex?如何使用拆分和正则表达式将字符串拆分为数组?
【发布时间】:2017-01-09 13:12:56
【问题描述】:

我要拆分的字符串如下:

#1 Single" (2006)\t\t\t\t\t2006-????

我正在尝试的正则表达式是:

(["#0-9 a-zA-Z]*\w") (\([0-9]*\w\)).*([0-9{4}]*\d-[\?0-9{4}]*)

然而,这需要整个字符串而不是部分。 如何将它变成一个数组?

array("\"#1 Single\"", "2006", "2006-????");

【问题讨论】:

  • array() 应该是什么,为什么不使用split() 方法?如果字符串的结构对于“简单”拆分来说过于复杂,请尝试 PatternMatcher 以及 group() 方法和简单的数组/集合操作。
  • 正如 Thomas 所说,使用 Matchergroup 属性来获取各个匹配组的值。

标签: java arrays regex string split


【解决方案1】:

您已经在正则表达式中对您感兴趣的不同部分进行了分组,因此您应该分别检索它们并使用它们来填充结果数组:

//assumes a Matcher matcher which has already matched the text with .find() or .matches()
int groupCount = 3;  // for more complex cases, use matcher.groupCount();
String[] parts = new String[groupCount];
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
    parts[groupIndex] = matcher.group(groupIndex);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多