拆分字符串('_'作为分隔符)

时间:2013-05-17 07:11:08

标签: java string parsing

我有以下字符串

String S1="S1_T1_VIEW";

我希望将它拆分并分配给字符串,如下所示:

String permission = "VIEW";
String component = "S1_T1";
String parent = "S1";

我尝试使用S1.split()功能,它没有多大帮助。

String也可以像这样

String S1="S1_T1_C1_DELETE";

那个时间结果应该是

String permission = "DELETE";
String component = "S1_T1_C1";
String parent = "S1_T1";

任何建议都会有所帮助。

提前致谢

2 个答案:

答案 0 :(得分:7)

我假设以下内容:

  • permissionS1跟随最后一个下划线的部分。
  • component是最后一个下划线之前S1的一部分。
  • parent最后一个下划线之前component的一部分。

如果是这样,请尝试以下方法?这基本上只是对上述规则的字面解释,通过查找适当的下划线来分割字符串。

int lastUnderscore = S1.lastIndexOf("_");
String permission = S1.substring(lastUnderscore + 1);
String component = S1.substring(0, lastUnderscore);
lastUnderscore = component.lastIndexof("_");
String parent = component.substring(0, lastUnderscore);

答案 1 :(得分:5)

我们也可以使用正则表达式。

private static final Pattern pattern = Pattern.compile("^((.+)_[^_]+)_([^_]+)$");

    final Matcher matcher = pattern.matcher(input);
    if (!matcher.matches()) {
        return null;
    }

    String permission = matcher.group(3);
    String component = matcher.group(1);
    String parent = matcher.group(2);

演示:http://ideone.com/NhZPI2