1 使用正则表达式
String name="CEO办公室[G&A]";
//String name="公司_IT信息服务部[G&A]_内网支持部[G&A]_内网资产组[G&A]";
Pattern p=Pattern.compile("\\[([^\\[\\]]*)\\]$");
//\\[([^\\[\\]]*)\\]$ ,$是匹配字符串结尾的意思
//([^\\[\\]]*这个是任意个不是‘[’ ‘]’的字符串
Matcher m=p.matcher(name);
if(m.find()){
name=m.group(1);
}else{
name="没有";
}
System.out.println(name);
2 使用字符串截取的方式
String name="CEO办公室[G&A]";
//String name="公司_IT信息服务部[G&A]_内网支持部[G&A]_内网资产组[G&A]";
int lastStart=name.lastIndexOf("[");
int lastEnd=name.lastIndexOf("]");
String name2=name.substring(lastStart+1, lastEnd);
System.out.println("name22:"+name2);
本文介绍两种从字符串中提取特定子串的方法:一种是使用正则表达式,另一种是通过字符串截取的方式实现。正则表达式方法利用模式匹配获取指定格式的子串;字符串截取方式则通过定位起始和结束位置来提取目标内容。

被折叠的 条评论
为什么被折叠?



