JavaでURLに対して、正規表現でマッチングをしたときのめも。。。
利用したメソッド
boolean java.lang.String.matches(String regex)
matches
public boolean matches(String regex)
この文字列が、指定された正規表現と一致するかどうかを判定します。
このフォームのメソッド呼び出し str.matches(regex) では、次の式と正確に同じ結果が得られます。
Pattern.matches(regex, str)
パラメータ:
regex - この文字列との一致を判定する正規表現
戻り値:
この文字列が指定された正規表現と一致する場合にだけ、true が返される
例外:
PatternSyntaxException - 正規表現の構文が無効な場合
導入されたバージョン:
1.4
関連項目:
Pattern
このブログのURLを例にして、マッチする場合としない場合を試してみる
"http://yamashiro0110.hatenadiary.jp".matches("http://([^.]+).hatenadiary.jp");
// true
"http://yamashiro.0110.hatenadiary.jp".matches("http://([^.]+).hatenadiary.jp");
// false
- "([^.]+)"で"."を含まないように指定しているので、2つめはfalse
"http://yamashiro0110.hatenadiary.jp".matches("http://yamashiro0110.hatenadiary.jp/?");
// true
"http://yamashiro0110.hatenadiary.jp/".matches("http://yamashiro0110.hatenadiary.jp/?");
// true
- 最後の"?"が直前の文字列が0回以上の場合にマッチすることを意味するので、"/"があってもなくてもマッチする
"http://yamashiro0110.hatenadiary.jp/entry000/".matches("http://yamashiro0110.hatenadiary.jp/([^/]+)/");
// true
"http://yamashiro0110.hatenadiary.jp/entry/000/".matches("http://yamashiro0110.hatenadiary.jp/([^/]+)/");
// false
- "([^/]+)"で"/"が入らない場合にマッチするように指定しているので、2つめはfalse
"http://yamashiro0110.hatenadiary.jp/hoge/".matches("http://yamashiro0110.hatenadiary.jp/(?!entry)([^/]+)/");
// true
"http://yamashiro0110.hatenadiary.jp/entry/".matches("http://yamashiro0110.hatenadiary.jp/(?!entry)([^/]+)/");
// false
- "(?!entry)([^/]+)"で"entry"を否定しているため、2つめはfalse