2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】文字列操作: 特定の文字列を語尾に含む場合に削除する方法

Posted at

本記事で紹介すること

Flutterの文字列(String)において、特定の文字列を含む場合、該当の語尾を削除する方法

解決方法

replaceAll関数を用いて、正規表現で文末を意味する"$"を使って、文末に特定の文字列が一致するかを検索して、空文字""で入れ替える。

実際のコード

main.dart
void main() {
  // 例の文字列
  String text1 = "bukunya";
  String text2 = "bukuku";
  String text3 = "bukumu";
  String text4 = "This is a test";

  // 文末が "nya"、"ku"、"mu" のいずれかであれば削除
  String result1 = removeEnding(text1);
  String result2 = removeEnding(text2);
  String result3 = removeEnding(text3);
  String result4 = removeEnding(text4);

  print(result1); // buku
  print(result2); // buku
  print(result3); // buku
  print(result4); // This is a test
}

String removeEnding(String input) {
  // 正規表現で文末の "nya"、"ku"、"mu" を削除
  return input.replaceAll(RegExp(r'(nya|ku|mu)$'), '');
}

DartPadで検証

image.png

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?