2016-11-28 52 views
0

我有以下代碼,試圖根據正則表達式(正則表達式())提取兩個單詞(球),但匹配程序沒有找到這些單詞。你可以幫我嗎?在java代碼中查找帶有模式的單詞

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 
+1

圓是圓的,球是一個球體 – yossico

+0

@yossico球是一個球體;所有球體都是圓形的;因此球是圓的。完美的三段論。 – khelwood

+1

你用完整的正則表達式'((| | | |什麼)(Peter | Luke | Hans | ball))'測試每個單詞。這是主要問題。 –

回答

0

你的主要問題是你測試每個單詞對完整正則表達式,((The|or|what) (Peter|Luke|Hans|ball))。您需要直接從句子中提取子字符串。

我試圖保持你的COSE儘可能:

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