如何使用split和regex将String拆分为数组?

时间:2017-01-09 13:12:57

标签: java arrays regex string split

我想要拆分的字符串如下:

sudo chown -R $YOUR_USER:www-data $DIRECTORY

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

composer require package/name

php artisan make:whatever

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

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

1 个答案:

答案 0 :(得分:2)

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

//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);
}