0

你叫什么名字?你好吗?我在路上。你在哪里?你饿了吗?我喜欢你。

在上一段中,答案应该选择所有 wh 问题,例如“你叫什么名字?你在哪里?”

如何在java中使用正则表达式实现上述目标?

4

2 回答 2

3

好的,我测试了这段代码,所以它现在应该可以工作了。它寻找Wh我能想到的所有英语单词,而不是试图Wh在一个单词中找到它自己。

String text = "What is your name? How do you do? I am in way. Where are you? Are you hungry? I like you. What about questions that contain a comma, like this one? Do you like my name, Whitney Houston? What is going to happen now, is you are going to do what I say. Is that clear? What's all this then?";

Pattern p = Pattern.compile("(?:Who|What|When|Where|Why|Which|Whom|Whose)(?:'s)?\\s+[^\\?\\.\\!]+\\?");
Matcher m = p.matcher(text);

List<String> questions = new ArrayList<String>();
while (m.find()) questions.add(m.group());

for (String question : questions) System.out.println(question);

我刚刚意识到可能有一个以 开头的问题Who's,所以现在它允许'sWh单词之后。

于 2013-01-04T16:41:23.520 回答
1

简单版(用于OP例句)...

    Pattern p = Pattern.compile("Wh[^\\?]*\\?");
    Matcher m = p.matcher(s);
    while (m.find()) {
            System.out.println(m.group());
    }

对于更高级的匹配(确保 Wh 词在句首)...

    Pattern p = Pattern.compile("(^|\\?|\\.) *Wh[^\\?]*\\?");
    Matcher m = p.matcher(s);
    while (m.find()) {
            String match = m.group().substring(m.group().indexOf("Wh"));
            System.out.println(match);
    }
于 2013-01-10T11:51:31.853 回答