如何重置正则表达式的模式?(How to reset the pattern of a regular expression?)
优质
小牛编辑
124浏览
2023-12-01
问题描述 (Problem Description)
如何匹配正则表达式中的重复单词?
解决方案 (Solution)
下面的示例演示如何使用p.matcher()方法和regex.Matcher类的m.group()方法在正则表达式中搜索重复的单词。
import java.util.Scanner;
import java.io.*;
import java.util.regex.*;
import java.util.ArrayList;
public class dupl {
public static void main(String[] args) {
ArrayList <String> manyLines = new ArrayList<String>();
ArrayList <String> noRepeat = new ArrayList<String>();
try {
String s1 = "Hello hello Hello there there past pastures ";
Scanner myfis = new Scanner(s1);
while(myfis.hasNext()) {
String line = myfis.nextLine();
String delim = System.getProperty("line.separator");
String [] lines = line.split(delim);
for(String s: lines) {
if(!s.isEmpty()&&s!=null) {
manyLines.add(s);
}
}
}
if(!manyLines.isEmpty()) {
System.out.print("Original text is:\n");
for(String s: manyLines) {
System.out.println(s);
}
}
if(!manyLines.isEmpty()) {
for(String s: manyLines) {
String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1");
noRepeat.add(result);
}
}
if(!noRepeat.isEmpty()) {
System.out.print("After Remove duplicates:\n");
for(String s: noRepeat) {
System.out.println(s);
}
}
} catch(Exception ex) {
System.out.println(ex);
}
}
}
结果 (Result)
上面的代码示例将产生以下结果。
Original text is:
Hello hello Hello there there past pastures
After Remove duplicates:
Hello there past pastures