Java如何创建字符串搜索并使用正则表达式替换?
在此示例中,您将看到我们如何使用Java中的正则表达式类创建一个小的搜索和替换程序。下面的代码会将所有的棕色词替换为红色。
package org.nhooo.example.regex;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class StringReplace {
public static void main(String[] args) {
String source = "The quick brown fox jumps over the brown lazy dog.";
String find = "brown";
String replace = "red";
//将给定的正则表达式编译为模式。
Pattern pattern = Pattern.compile(find);
//创建一个匹配器,将匹配给定输入与
//模式。
Matcher matcher = pattern.matcher(source);
//替换匹配输入序列的每个子序列
//具有给定替换字符串的模式。
String output = matcher.replaceAll(replace);
System.out.println("Source = " + source);
System.out.println("Output = " + output);
}
}代码段的结果是:
Source = The quick brown fox jumps over the brown lazy dog. Output = The quick red fox jumps over the red lazy dog.
热门推荐
10 古文毕业赠言祝福语简短
11 花小卡片祝福语简短
12 参加省运会祝福语简短英语
13 公司团建周年祝福语简短
14 结婚祝福语嫂子的话简短
15 日语贺卡日常祝福语简短
16 基金赚钱祝福语简短英文
17 男生打球祝福语简短独特
18 客户蛋糕生日祝福语简短