【发布时间】:2016-11-28 13:28:15
【问题描述】:
我有以下代码,试图根据正则表达式(regex())提取两个词(球),但匹配器没有找到这些词。你能帮帮我吗?
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
【问题讨论】:
-
圆是圆的,球是球体
-
@yossico 球是一个球体;所有球体都是圆的;因此球是圆的。完美的三段论。
-
您针对完整的正则表达式
((The|or|what) (Peter|Luke|Hans|ball))测试每个单词。这是主要问题。 -
@yossico 一个球可以是圆的。
-
非常感谢!