繁体   English   中英

分割字符串(以'_'作为分隔符)

[英]splitting a string('_' as delimiter)

我有以下字符串

String S1="S1_T1_VIEW";

我希望将其拆分并分配给这样的字符串:

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

我尝试使用S1.split()函数并没有太大帮助。

字符串也可以像这样

String S1="S1_T1_C1_DELETE";

那个时间结果应该是

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

任何的意见都将会有帮助 。

提前致谢

我假设以下内容:

  • permission是最后一个下划线之后的S1的一部分。
  • component是最后一个下划线之前的S1的一部分。
  • parentcomponent 最后一个下划线之前的部分。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM