単語のリストがあります: dog、cat、leopard。
Javaで正規表現を考え出して、単語のいずれかを含む長い段落から文を抜き出そうとしています(大文字と小文字は区別されません)。文は.
?
orで終わり!
ます。ありがとうございました!
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)[^.?!]*?[.?!]"
以下では、文が大文字で始まり、 文の最後以外に.
、!
またはがないことを前提としています。?
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.
. (猫|犬|ヒョウ)。(\.|\?|\!)$ であり、java.util.regex.Pattern の CASE_INSENSITIVE オプションを使用する必要があります。