LoginSignup
3
2

More than 5 years have passed since last update.

エラー『Dangling meta character '?'』の回避方法

Last updated at Posted at 2015-07-14

Javaのmatches関数を用いた文字列比較で
Dangling meta character '?' near index 0
というエラーが発生したので対策メモ.

エラー発生状況

matches関数で二つのString変数の比較を行ったときに発生.
具体的には,

String str1 = "?ABC";
String str2 = "?A";

if(str1.matches(str2 + ".*)) {}

というように,文字列の先頭に?が含まれる変数の比較を行った.

原因

文字列中の?が正規表現記号と判定されてしまうため.

回避方法

matches関数の引数の文字列にエスケープ文字\\をつけてあげればOK.
上記の例だと,次のようにすれば回避できる.

String str1 = "?ABC";
String str2 = "?A";

if(str1.matches("\\" + str2 + ".*")) {}

もしくは,Pattern.quoteでも回避できる.

if(str1.matches(Pattern.quote(str2) + ".*")) {}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2