文字列が特定の文字や文字列で終わっているかどうかを見るには (end_with? / endsWith)

Java

if (str.endsWith(suffix)) {
    System.out.println("Match!");
} else {
    System.out.println("Unmatch!");
}

Scala

if (str.endsWith(suffix)) {
  println("Match!");
} else {
  println("Unmatch!");
}

PHP

function endsWith($str, $suffix) {
    $len = strlen($suffix);
    return $len == 0 || substr($str,  strlen($str) - $len, $len) === $suffix;
    // $str が $suffix より短くてもエラーにはならずに false になる
}

if (endsWith($str, $suffix)) {
    echo "Match!\n";
} else {
    echo "Unmatch!\n";
}

Python

if str.endswith(suffix):
    print("Match!")
else:
    print("Unmatch!")

Ruby

if str.end_with?(suffix)
  puts "Match!"
else
  puts "Unmatch!"
end

Perl

if ($str =~ (quotemeta($suffix) . '\z')) {
    print "Match!";
} else {
    print "Unmatch!";
}

関連

Java / Scala

Signature:

boolean java.lang.String#endsWith(String suffix)

java.lang.String#endsWith | Java Platform SE 8 Javadoc
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#endsWith-java.lang.String-

PHP

これを簡単にやる関数はないようなので、例えば以下のような関数を作る。

function endsWith($str, $suffix) {
    $len = strlen($suffix);
    return $len == 0 || substr($str,  strlen($str) - $len, $len) === $suffix;
    // $str が $suffix より短くてもエラーにはならずに false になる
}

Python

文字列にある endswithメソッドを使う。

str = "abcabc"

print str.endswith("ab")
# => False

print str.endswith("bc")
# => True

string.endswith | Python 2.7 documentation
http://docs.python.jp/2/library/stdtypes.html#str.endswith

string.endswith | Python 3 documentation
http://docs.python.jp/3/library/stdtypes.html#str.endswith

Ruby / JRuby

文字列にある end_with? メソッドを使う。

str.end_with?(suffix)

Perl

文字列の最後にマッチする正規表現 \z を使う。

print "abc" =~ /bc\z/; # => 1

接尾辞が変数の場合、その変数から正規表現を組み立てる。

print $str =~ (quotemeta($suffix) . '\z');

上記例のように正規表現全体を () で囲む必要があり、囲まないと =~ のほうが先に結合してしまって、常にmatchしてしまう。

JavaScript

よく使う方法。

str.substr(str.length - suffix.length) == prefix

ただ、これだと、suffixstrより長い場合にどうなることやら。

このサイトは筆者(hydrocul)の個人メモの集合です。すべてのページは永遠に未完成です。
スポンサーリンク