Web サイトから取得した教科書の定義に正規表現を一致させようとしています。定義には常に、新しい行の後に定義が続く単語があります。例えば:
Zither
Definition: An instrument of music used in Austria and Germany It has from thirty to forty wires strung across a shallow sounding board which lies horizontally on a table before the performer who uses both hands in playing on it Not to be confounded with the old lute shaped cittern or cithern
単語 (この場合は "Zither") だけを取得しようとすると、改行文字を取得し続けます。
私は両方を試しましたが、あまり運が^(\w+)\s
ありませんでした。たぶんうまくいく^(\S+)\s
と思いましたが、それは言葉とまったく一致していないようです。http://rubular.com/r/LPEHCnS0ri ; ^(\S+)$
rubular でテストしてきました。Javaがそうではないという事実にもかかわらず、これは私のすべての試みを私が望むようにうまく一致させているようです。
ここに私のスニペットがあります
String str = ...; //Here the string is assigned a word and definition taken from the internet like given in the example above.
Pattern rgx = Pattern.compile("^(\\S+)$");
Matcher mtch = rgx.matcher(str);
if (mtch.find()) {
String result = mtch.group();
terms.add(new SearchTerm(result, System.nanoTime()));
}
これは、結果の文字列をトリミングすることで簡単に解決できますが、既に正規表現を使用している場合は不要なようです。
すべてのヘルプは大歓迎です。前もって感謝します!