掌握Java正则表达式函数的基本用法
正则表达式是一种用来匹配字符串的特殊模式,它可以用来验证输入的格式、搜索相应的内容等,Java语言中也提供了一套正则表达式函数库,本文将介绍Java正则表达式函数的基本用法。
Java提供的正则表达式函数可以分为两类:字符串匹配函数和字符串替换函数。
一、字符串匹配函数
1. matches方法
matches方法用来测试字符串是否与指定的正则表达式匹配,返回值为布尔类型。
示例代码如下:
String str = "hello world";
boolean b = str.matches(".*world.*");
System.out.println(b);
2. split方法
split方法用来将字符串按照指定的正则表达式分割成多个子字符串,返回值为一个字符串数组。
示例代码如下:
String str = "hello,world";
String[] arr = str.split(",");
for(String s : arr){
System.out.println(s);
}
3. find方法
find方法用来搜索字符串中出现的下一个与正则表达式匹配的子字符串,返回值为布尔类型。
示例代码如下:
String str = "hello world";
Pattern pattern = Pattern.compile("world");
Matcher matcher = pattern.matcher(str);
boolean b = matcher.find();
System.out.println(b);
二、字符串替换函数
1. replaceAll方法
replaceAll方法用来将字符串中所有与正则表达式相匹配的子字符串替换成指定的内容,返回值为替换后得到的新字符串。
示例代码如下:
String str = "hello 123";
String s = str.replaceAll("\\d+", "world");
System.out.println(s);
2. replaceFirst方法
replaceFirst方法用来将字符串中第一个与正则表达式相匹配的子字符串替换成指定的内容,返回值为替换后得到的新字符串。
示例代码如下:
String str = "hello 123";
String s = str.replaceFirst("\\d+", "world");
System.out.println(s);
以上就是Java正则表达式函数的基本用法,掌握了这些函数的用法后,在实际应用中就可以更加灵活地进行字符串处理。
