蔡香满屋
站在牛顿头上吃苹果

今天项目中遇到需要截取一段字符串中的某段特定的值。格式为:(  ( GLDWH = '14000' )  ) 。目的:取到14000

于是有两种解决方式:

第一种,使用字符串截取的方式:substring

String str = "(  ( GLDWH = '14000' )  )";

int first = str.indexOf("'"); //单引号第一次出现的位置
int last = str.lastIndexOf("'"); //单引号最后一次出现的位置
String aa = str.substring(first+1, last);//截取后变成新的字符串
System.out.println(aa); //14000

===================================

第二种方式,使用正则表达式匹配:

其中:

Pattern: 一个Pattern是一个正则表达式经编译后的表现模式。 

Matcher: 一个Matcher对象是一个状态机器,它依据Pattern对象做为匹配模式对字符串展开匹配检查。

 

String str = "(  ( GLDWH = '14000' )  )";

Pattern pattern = Pattern.compile("([\'\"])(.*?)\\1");
Matcher matcher = pattern.matcher(str );
if (matcher.find()) {
String collegeId = matcher.group(2); 

System.out.println("collegeld");//14000
}

  

 

posted on 2018-08-31 16:17  蔡香满屋  阅读(27277)  评论(0)    收藏  举报