近日遇到小测试题,要求把例如“-124abaad>132”类型字符串,转化为“-124”,也就是说截取前部分整数。
重温了正则表达式,我的写法是:"^([-+]?)([0-9]+)(.*)"
把待处理字符串分组,后面用Matcher的gourp(int count)把整数提取出来转型就行。
开始一下代码一直报错:
错误如下:
后来,终于找到原因,把注释行的注释去掉,就正常了。得先matches()一下,才能对字符串进行匹配,开始的matcher(String s)只是用于生成Matcher,并没有进行匹配。
重温了正则表达式,我的写法是:"^([-+]?)([0-9]+)(.*)"
把待处理字符串分组,后面用Matcher的gourp(int count)把整数提取出来转型就行。
开始一下代码一直报错:
String p3="^([-+]?)([0-9]+)(.*)";
Pattern pattern=Pattern.compile(p3);
System.out.println(pattern.pattern());
Matcher m=pattern.matcher(s);
// System.out.println(m.matches());
for(int i=0;i<m.groupCount();i++)
System.out.println(m.group(i+1));
错误如下:
Exception in thread "main" java.lang.IllegalStateException: No match found
后来,终于找到原因,把注释行的注释去掉,就正常了。得先matches()一下,才能对字符串进行匹配,开始的matcher(String s)只是用于生成Matcher,并没有进行匹配。