1

単語のリストがあります: dogcatleopard

Javaで正規表現を考え出して、単語のいずれかを含む長い段落から文を抜き出そうとしています(大文字と小文字は区別されません)。文は. ?orで終わり! ます。ありがとうございました!

4

5 に答える 5

3

仮定

  • 文は大文字で始め、に行末記号 [.?!] を入れないでください。
  • キーワード マッチでは大文字と小文字が区別されません。ただし、部分文字列の一致は無効です。
  • キーワードは、文のどこ (最初、最後、または途中) でも使用できます。
  • 引用と非公式の二重句読点をサポートします。必要がない場合は、2 番目の正規表現を使用します。

public class SentenceFinder {

    public static void main(String[] args) {
        String paragraph = "I have a list of words to match: dog, cat, leopard. But blackdog or catwoman shouldn't match. Dog may bark at the start! Is that meow at the end my cat? Some bonus sentence matches shouldn't hurt. My dog gets jumpy at times and behaves super excited!! My cat sees my goofy dog and thinks WTF?! Leopard likes to quote, \"I'm telling you these Lions suck bro!\" Sometimes the dog asks too, \"Cat got your tongue?!\"";
        Pattern p = Pattern.compile("([A-Z][^.?!]*?)?(?<!\\w)(?i)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]{1,2}\"?");
        Matcher m = p.matcher(paragraph);
        while (m.find()) {
            System.out.println(m.group());
        }
    }
    /* Output:
       I have a list of words to match: dog, cat, leopard.
       Dog may bark at the start!
       Is that meow at the end my cat?
       My dog gets jumpy at times and behaves super excited!!
       My cat sees my goofy dog and thinks WTF?!
       Leopard likes to quote, "I'm telling you these Lions suck bro!"
       Sometimes the dog asks too, "Cat got your tongue?!"
    */
}


「Quotes?!」の場合の単純化された正規表現 (または非公式の句読点) は必要ありません:
"([A-Z][^.?!]*?)?(?<!\\w)(?i)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]"

大文字で始まらない文も取得するには (入力にそのようなタイプミスがある場合):
"(?i)([a-z][^.?!]*?)?(?<!\\w)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]"

于 2013-04-13T23:27:47.097 に答える
3

以下では、文が大文字で始まり、 文の最後以外に.!またはがないことを前提としています。?

String str = "Hello. It's a leopard I think. How are you? It's just a dog or a cat. Are you sure?";
Pattern p = Pattern.compile("[A-Z](?i)[^.?!]*?\\b(dog|cat|leopard)\\b[^.?!]*[.?!]");
Matcher m = p.matcher(str);

while (m.find()) {
    System.out.println(m.group());
}
// It's a leopard I think.
// It's just a dog or a cat.
于 2013-04-13T17:47:48.547 に答える
0

. (猫|犬|ヒョウ)。(\.|\?|\!)$ であり、java.util.regex.Pattern の CASE_INSENSITIVE オプションを使用する必要があります。

于 2013-04-13T17:40:27.127 に答える