在 java 代码中查找具有模式的单词

Find words with pattern on java code

我有以下代码,试图根据正则表达式 (regex()) 提取两个词 (The ball),但匹配器没有找到这些词。你能帮帮我吗?

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class change1 {
    private static String[] sentence_to_array;
    public static void main(String[] args) {
        String sentence = "The ball is round";
        sentence_to_array = sentence.split(" ");        
        Pattern p = null;
        Matcher m = null;
        String to_remove = findings(p, m, sentence_to_array, regex());
    }//method
    private static String findings(Pattern p, Matcher m, String[] pieces, String fr) {
        String word = "";
        pieces = sentence_to_array;
        p = Pattern.compile(fr);
        for (String piece : pieces) {
            m = p.matcher(piece);
            if (m.find()) {
                word = word.concat(piece + " ");
            }//if
        }//for
        return word;
    }//method
    public static String first_regex() {
        return "(The|or|what)";
    }//Method
    public static String second_regex() {
        return "(Peter|Luke|Hans|ball)";
    }//method
    public static String regex() {//επιστρέφει το υποκείμενο ως regex
        return "(" + first_regex() + " " + second_regex() + ")";
    }//method
}//class

您的主要问题是您针对完整的正则表达式测试每个单词,((The|or|what) (Peter|Luke|Hans|ball))。您需要直接从句子中提取子串。

我尽可能地保护了你的健康:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
    private static String[] sentence_to_array;
    public static void main (String[] args) throws java.lang.Exception
    {
        String sentence = "The ball is round";
        Pattern p = null;
        Matcher m = null;
        System.out.println(findings(p, m, sentence, regex()));
    }
    private static List<String> findings(Pattern p, Matcher m, String pieces, String fr) {
        p = Pattern.compile(fr);
        m = p.matcher(pieces);
        List<String> lst = new ArrayList<>();
        while (m.find()) {
            lst.add(m.group());
        }//for
        return lst;
    }//method
    public static String first_regex() {
        return "(The|or|what)";
    }//Method
    public static String second_regex() {
        return "(Peter|Luke|Hans|ball)";
    }//method
    public static String regex() {//επιστρέφει το υποκείμενο ως regex
        return "(" + first_regex() + " " + second_regex() + ")";
    }//method
}

Java demo