文字列を分割するためのJavaのデフォルト/簡単な方法はありますが、引用符やその他の記号を処理しますか?
たとえば、次のテキストがあるとします。
There's "a man" that live next door 'in my neighborhood', "and he gets me down..."
入手:
There's
a man
that
live
next
door
in my neighborhood
and he gets me down
文字列を分割するためのJavaのデフォルト/簡単な方法はありますが、引用符やその他の記号を処理しますか?
たとえば、次のテキストがあるとします。
There's "a man" that live next door 'in my neighborhood', "and he gets me down..."
入手:
There's
a man
that
live
next
door
in my neighborhood
and he gets me down
入力に対して次のようなものが機能します。
String text = "There's \"a man\" that live next door "
+ "'in my neighborhood', \"and he gets me down...\"";
Scanner sc = new Scanner(text);
Pattern pattern = Pattern.compile(
"\"[^\"]*\"" +
"|'[^']*'" +
"|[A-Za-z']+"
);
String token;
while ((token = sc.findInLine(pattern)) != null) {
System.out.println("[" + token + "]");
}
上記の出力 ( ideone.com で見られるように):
[There's]
["a man"]
[that]
[live]
[next]
[door]
['in my neighborhood']
["and he gets me down..."]
を使用しますScanner.findInLine
。正規表現パターンは次のいずれかです。
"[^"]*" # double quoted token
'[^']*' # single quoted token
[A-Za-z']+ # everything else
間違いなく、これが常に 100% 機能するとは限りません。引用符をネストできる場合などは注意が必要です。
あなたの論理に基づいて疑わしいですが、アポストロフィと一重引用符を区別していますThere's
。in my neighborhood
上記のものが必要な場合は、何らかのペアリング ロジックを開発する必要があります。正規表現を考えています。または、ある種の 2 部分解析。