Skip to content

Instantly share code, notes, and snippets.

@okstring
Created September 9, 2021 12:32
Show Gist options
  • Save okstring/cd258187073c515252ebebbad7d248b0 to your computer and use it in GitHub Desktop.
Save okstring/cd258187073c515252ebebbad7d248b0 to your computer and use it in GitHub Desktop.

정규표현식

NSRegularExpreession API를 사용해 regex 패턴을 넣고 유효하면 matches, numberOfMatches 등 메소드를 사용해 추출한다

String 에는 replacingOccurrences 에도 정규식을 사용할 수 있다.

import Foundation

extension String {
    // Bool
    func isMatch(for regex: String) -> Bool {
        guard let regex = try? NSRegularExpression(pattern: regex) else {
            return false
        }
        
        return regex.matches(in: self, range: NSRange(self.startIndex..., in: self)).count > 0
    }
    
    // replace
    func replace(regex: String, with replaced: String) -> String {
        return self.replacingOccurrences(of: regex, with: replaced, options: [.regularExpression])
    }
        
    // 매치 숫자
    func numberOfMatches(for regex: String) -> Int {
        guard let regex = try? NSRegularExpression(pattern: regex) else {
            return 0
        }
        
        return regex.numberOfMatches(in: self, options: .reportCompletion, range: NSRange(self.startIndex..., in: self))
    }
    
    //array로 리턴
    func getArrayAfterRegex(regex: String) -> [String] {
        guard let regex = try? NSRegularExpression(pattern: regex) else {
            return []
        }
        
        let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))
        
        return results.map {
            String(self[Range($0.range, in: self)!])
        }
    }
}



var str = "Hello  Hello #hi #Hello ##nam WOW www Hello"
 
//End
print(str.getArrayAfterRegex(regex: "Hello$"))

// OR
print(str.getArrayAfterRegex(regex: "Hello|hi"))

// 3개씩
print(str.getArrayAfterRegex(regex: "..."))
print(str.getArrayAfterRegex(regex: ".{3}"))

//A-Z 한 글자 제거, 괄호 안에 ^는 부정의 의미
print(str.getArrayAfterRegex(regex: "[^A-Z]"))

let test = "aabc abc bc"
// * 0~, + 1~, ? 0,1, \\s
print(test.getArrayAfterRegex(regex: "a*b"))
print(test.getArrayAfterRegex(regex: "a+b"))
print(test.getArrayAfterRegex(regex: "a?b"))
print(test.getArrayAfterRegex(regex: "c "))


str = "Hello  Hello #hi #Hello ##nam WOW www Hello"

print(str.getArrayAfterRegex(regex: "l. "))
print(str.getArrayAfterRegex(regex: "[^#]"))

print("09:09".getArrayAfterRegex(regex: "[0-9]+"))

reference

https://eunjin3786.tistory.com/12

https://tngusmiso.tistory.com/62

https://regexone.com/lesson/more_groups?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment