Java按正则提取字符串


今天项目中遇到需要截取一段字符串中的某段特定的值。格式为:(  ( 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
}

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM