7
6

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.

[swift]文字列が半角数字かどうかを判定する

Posted at

コード

文字列チェックの記事は色々あるのですが、半角と全角がチェックできていなかったりと
正解はなんなのだ???と考えてしまったので記します!

swift
import UIKit

class ViewController: UIViewController {
    
    let hanMoji: String = "01234"
    let zenMoji: String = "01234"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if hanMoji.isAlphanumeric() {
            print("hanMojiは半角数字")
        }else{
            print("hanMojiは全角数字")
        }
        
        if zenMoji.isAlphanumeric() {
            print("zenMojiは半角数字")
        }else{
            print("zenMojiは全角数字")
        }
    }
}

extension String {
    // 半角数字の判定
    func isAlphanumeric() -> Bool {
        return self.range(of: "[^0-9]+", options: .regularExpression) == nil && self != ""
    }
}
出力結果
hanMojiは半角数字
zenMojiは全角数字

正規表現ってなかなか慣れないんですよね・・・

7
6
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?