zoukankan      html  css  js  c++  java
  • Java如何在正则表达式中匹配重复单词?

    在Java编程中,如何在正则表达式中匹配重复单词?

    以下示例显示了如何使用regex.Matcher类的p.matcher()方法和m.group()方法在正则表达式中搜索重复的单词。

    package com.yiibai;
    
    import java.util.Scanner;
    import java.io.*;
    import java.util.regex.*;
    import java.util.ArrayList;
    
    public class SearchingDuplicateWords {
        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:
    ");
                    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:
    ");
                    for (String s : noRepeat) {
                        System.out.println(s);
                    }
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    Original text is:
    Hello hello Hello there there past pastures 
    After Remove duplicates:
    Hello there past pastures
  • 相关阅读:
    Longest Palindromic Substring
    PayPal MLSE job description
    Continuous Median
    Remove Duplicates From Linked List
    Valid IP Address
    Longest substring without duplication
    Largest range
    Subarray sort
    Multi String Search
    Suffix Trie Construction
  • 原文地址:https://www.cnblogs.com/borter/p/9617144.html
Copyright © 2011-2022 走看看