NIk Tsiv NIk Tsiv - 11 days ago 8
Java Question

Find words with pattern on java code

I have the following code, trying to extract two words(The ball) based on a regex(regex()), but matcher does not find these words. Can you help me?

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

Answer

Your main issue is that you test each word against a full regex, ((The|or|what) (Peter|Luke|Hans|ball)). You need to extract the substrings from the sentence directly.

I tried to preserve your cose as much as possible:

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
}

See the Java demo