14
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinで文字列が部分一致かどうかを判別

Posted at

文章中に特定の文字「TEXT」があるかどうか判別する。

このときトリプルクォート("""文字列""")にすると、エスケープせずにそのままの文字列を探せる。

###部分一致(返り値はBoolean)

val regex = Regex("TEXT")

val result = regex.containsMatchIn("aaa")
// --> false
val result = regex.containsMatchIn("aaaTEXT")
// --> true

###全文一致(返り値はBoolean)

val regex = Regex("TEXT")

val result = regex.matches("aaaTEXT")
// --> false
val result = regex.matches("TEXT")
// --> true

###前方一致

startsWithを使う。


val text1 = "aaaTEST"
val text2 = "TESTaaa"

result = text1.startsWith("TEST")
// -> false
result = text2.startsWith("TEST")
// -> true

###後方一致

endsWithを使う。


val text1 = "aaaTEST"
val text2 = "TESTaaa"

result = text1.endsWith("TEST")
// -> true
result = text2.endsWith("TEST")
// -> false
14
8
1

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
14
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?