0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】正規表現を使って全角数字の有無をチェックする方法

Posted at

check_zenkaku_digit メソッド解説

「正規表現の使いみちがよくわからない」という声を新人エンジニア聞くことがあります。ここでは、全角数字を含むかどうかを判定する関数を例に、正規表現の基本的な仕組みを解説します。

import re

def check_zenkaku_digit(hankaku_number):
    return bool(re.search(r'[0-9]', hankaku_number))

1. bool() 関数

  • 概要: 任意のオブジェクトの真偽値を返す関数です。
  • ポイント: None や空文字列、空のリストは False として扱われ、その他は True として扱われます。
print(bool(1))          # True
print(bool(0))          # False
print(bool('Hello'))    # True
print(bool(''))         # False
print(bool([]))         # False
print(bool([1, 2, 3]))  # True

2. re.search() 関数

  • 概要: 正規表現パターンを用いて、文字列の中から最初にマッチする部分文字列を探します。
  • ポイント: 一致が見つかるとマッチオブジェクトを返し、見つからない場合は None を返します。
import re

check_pattern = r'abc'
text = '123abc456'
match = re.search(check_pattern, text)

if match:
    print('マッチしました:', match.group())  # マッチした部分を表示
else:
    print('マッチしませんでした')

実行結果

マッチしました: abc

3. r'[0-9]' (正規表現パターン)

  • 概要: 全角数字(0から9)にマッチする正規表現パターンです。
  • ポイント: [] を使った範囲指定で、連続する全角数字をカバーします。r生文字列 (raw string) を意味し、エスケープシーケンスを無視します。
import re

pattern = r'[0-9]'
text = '123456'
match = re.search(pattern, text)

if match:
    print('マッチしました:', match.group())
else:
    print('マッチしませんでした')

実行結果

マッチしました: 4

まとめ: contains_zenkaku_digit メソッド

上述した仕組みを組み合わせると、以下のようにして全角数字を検出できます。

def contains_zenkaku_digit(hankaku_number):
    return bool(re.search(r'[0-9]', hankaku_number))

解説

  1. re.search(r'[0-9]', hankaku_number)

    • 文字列 hankaku_number 内に全角数字が含まれているかを検索します。
    • 一致する文字があればマッチオブジェクト、なければ None を返します。
  2. bool()

    • re.search() の戻り値を真偽値に変換します。
    • マッチオブジェクト ⇒ TrueNoneFalse

使用例

print(contains_zenkaku_digit('145'))     # False (全角数字なし)
print(contains_zenkaku_digit('125'))  # True  (全角数字あり)

これにより、文字列に全角数字が含まれているかどうかを簡単に判定できるようになります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?