Java程序设计之正则表达式

时间:2023-03-09 08:57:54
Java程序设计之正则表达式

  正则表达式平时在用到字符串处理的时候是比较常用的,个人觉得不需要刻意的去理解,用的话把文档拿出来查一下就好了,下面给个链接

  http://www.php100.com/manual/Javascript/html/jsgrpRegExpSyntax.htm

  这个是正则表达式的文档,用的时候可以去查查,下面用一个小例子熟悉一下,功能是输入一串字符串,输出里面的数字个数,代码比较简单:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class reg_test1 { public static void main(String[] args) {
reg_test1 rt = new reg_test1();
rt.function();
} public void function(){
int count = 0;
Pattern p = Pattern.compile("(\\d+)");
Scanner s = new Scanner(System.in);
Matcher m =p.matcher(s.nextLine());
while(m.find()){
count++;
}
System.out.println(count);
} }