Skip to content

Instantly share code, notes, and snippets.

@KatagiriSo
Last active September 29, 2020 08:34
Show Gist options
  • Save KatagiriSo/88cadc1b9eca8de0ae7827f586061f28 to your computer and use it in GitHub Desktop.
Save KatagiriSo/88cadc1b9eca8de0ae7827f586061f28 to your computer and use it in GitHub Desktop.
NSRegularExpression syntax suger
//
// main.swift
// Reg
//
// Created by KatagiriSo on 2017/10/17.
// Copyright © 2017年 RodhosSoft. All rights reserved.
//
import Foundation
extension NSString {
func selfRange() -> NSRange {
let str = self as String
if str.isEmpty {
return NSRange(location: 0, length: 0)
}
return self.range(of: self as String)
}
}
extension String {
func selfRange() -> NSRange {
return (self as NSString).selfRange()
}
func firstMatch(pattern:String, options:NSRegularExpression.Options = [], matchOptions:NSRegularExpression.MatchingOptions = [] ) -> NSTextCheckingResult? {
guard let reg = try? NSRegularExpression(pattern: pattern, options:options) else {
return nil
}
return reg.firstMatch(in: self,
options: matchOptions,
range: self.selfRange() )
}
func isInteger() -> Bool {
return firstMatch(pattern: "[0-9]*")?.range.toRange() == self.selfRange().toRange()
}
}
extension NSTextCheckingResult {
func show() {
print("\(self.range.location) - \(self.range.length)")
}
}
func integerTest(text:String) {
print(" \(text) ... \(text.isInteger())")
}
"12345".firstMatch(pattern: "[0-9]*")?.show()
"12a345".firstMatch(pattern: "[0-9]*")?.show()
"a12345".firstMatch(pattern: "[0-9]*")?.show()
integerTest(text: "1928491")
integerTest(text: "1934712947239851209452398")
integerTest(text: "1293481209348120934812094a123041203984013294")
integerTest(text: "")
integerTest(text: " 120312903129038210")
integerTest(text: "1293812 2103123")
integerTest(text: "\n23")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment