该java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。该类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取该类的对象。
这个(Matcher)类的replaceFirst()方法接受一个字符串值,并用给定的字符串值替换输入文本中的第一个匹配子序列,并返回结果。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#]";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//检索使用的模式
System.out.println("The are character # occurred "+count+" times in the given text");
//替换第一次出现的情况
String result = matcher.replaceFirst("@");
System.out.println("Text after replacing the first occurrence of # with @ \n"+result);
}
}输出结果
Enter input text: Enter input text: Hello# How # are# you #welcome to Tutorials#point The are character # occurred 5 times in the given text Text after replacing the first occurrence of # with @ Hello@ How # are# you #welcome to Tutorials#point
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\s+";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
//用单个空格替换所有空格字符
String result = matcher.replaceFirst("_");
System.out.print("Text after replacing the first space with '_': \n"+result);
}
}输出结果
Enter a String hello this is a sample text with irregular spaces Text after replacing the first space with '_': hello_this is a sample text with irregular spaces