LoginSignup
0
0

【flutter】住所の都道府県のみ表示したい

Last updated at Posted at 2024-06-04

こんにちは!
今回は文字列の一部を表示させる方法について紹介します。

実装例

Screenshot_1717472605.png

コード

リストの内容をそのまま表示


//リスト
List<String> sampleList = [
  "東京都品川区",
  "埼玉県川越市",
  "神奈川県横浜市",
  "千葉県木更津市",
  "栃木県佐野市",
  "群馬県高崎市",
  "茨城県水戸市",
  "山梨県富士吉田市"
];
//リストを使って各住所を表示
children: sampleList.map((sampleText) {
  return Center(
    child: Text(
      sampleText,
      style: const TextStyle(
        fontSize: 15,
        fontWeight: FontWeight.w600,
      ),
    ),
  );
}).toList(),

リストの内容から都道府県を切り取って表示

//正規表現の定義:
 RegExp regExp = RegExp(r'(東京都|北海道|(?:京都|大阪)府|.{2,3}県)');
children: sampleList.map((sampleText) {
  // 各住所から都道府県部分を抽出
  Match? match = regExp.firstMatch(sampleText);
  String addressText =
      match != null ? match.group(0)! : '都道府県を選択してください';
  return Center(
    child: Text(
      addressText,
      style: const TextStyle(
        fontSize: 15,
        fontWeight: FontWeight.w600,
      ),
    ),
  );
}).toList(),

RegExpとは?

正規表現(RegExp)は、文字列のパターンを表現するための記法です。これは、特定の文字列パターンを検索、抽出、置換、一致させるために使用されます。また、検索対象の文字列内でパターンに一致する部分文字列を見つけるための柔軟な方法を提供します。これにより、テキストデータを効率的に操作し、必要な情報を取得することができます。

終わりに

今回の記事は以上になります。
今回も最後まで読んでいただきありがとうございました。
では、また次の記事で〜!

0
0
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
0
0