📌 이 포스팅은 NSRegularExpression 없이 정규식을 사용하는 방법에 대해 포스팅하였습니다. NSRegularExpression에 대한 내용은 아래 링크들을 확인해주세요.
- NSRegularExpression 공식문서
https://developer.apple.com/documentation/foundation/nsregularexpression
Apple Developer Documentation
developer.apple.com
- 스위프트에서 정규식 사용하는 방법( NSRegularExpression을 사용한 예)
https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift
How to use regular expressions in Swift
Match a variety of text using NSRegularExpression.
www.hackingwithswift.com
계절학기로 자바 프로그래밍 수업이 끝나고 나니 블로그 포스팅을 쓸 짬이 드디어 나네요. 21년도 회고와, 자격증 후기글, 스위프트 공부글 등 밀린 글은 많지만, 정규식은 NSRegularExpression 관련글이 되게 많더라구요. 간단하게 String 객체의 메서드를 이용하여 정규표현식의 패턴과 문자열을 매칭하는 방법을 정리하고자 포스팅해봅니다.
1. 정규표현식 패턴 체험해보기
RegExr: Learn, Build, & Test RegEx
RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).
regexr.com
위 사이트에서 정규식 패턴을 체크해볼 수 있습니다. 예를 들어 제가 슬래시로 감싸져있는 /한글/로만 된 두글자의 단어를 찾고 싶다면 아래처럼 해볼 수 있을거에요.
정규식에 맞는 텍스트만 하늘색으로 하이라이트 된 것을 확인할 수 있어요.
사이트내에서 치트시트 메뉴를 클릭하면 따로 정규식을 공부하지 않아도 바로 참고하여 사용할 수 있는 예제들이 있고요.
커뮤니티 패턴을 클릭하면 다른 사람들이 이미 만들어둔 정규식 패턴을 찾아볼 수 있어요.
2. SWIFT에서 정규표현식을 단 한줄로 간편하게 사용하는 방법
// 꼭 import 해주어야 가능
import Foundation
( 검사할문자열_또는_문자열변수).range(
of: 정규식패턴_또는_변수, options: .regularExpression) != nil ))
Foundation을 import한 후, 위와 같이 String의 .range 메서드를 이용하여 정규표현식 매칭 여부를 검사할 수 있습니다. 문자열 변수의 값이 없을 경우 등 nil값이 반환될 수 있기 때문에 해당값이 nil 인지 먼저 검사해야 합니다. 위의 리턴값은 boolean 값으로 반환되기 때문에 해당메서드를 조건문의 조건으로 넣거나, 혹은 필요에 따라 함수를 따로 만들어 해당 함수의 리턴값으로 지정해주면 될 것 같습니다.
예를 들어 휴대폰 번호를 체크한다고 하면 아래처럼 사용할 수 있겠습니다.
cellPhonne 변수에 검사할 문자열을, patternCellPhone에는 정규식 패턴을 입력하고 해당 스트링에 .range(of: 정규식패턴(또는 패턴이 저장된 문자열변수), options: .regularExpression) 메서드를 이용하여 isValidCellPhone 변수에 저장하였습니다.
String cellPhone = "010-123-1234"
String patternCellPhone = #"^\(?\d{3}\)?[ -]?\d{3,4}[ -]?\d{4}$"#
var isValidCellPhone =
cellPhone.range(of: patternCellPhone, options: .regularExpression ) != nil)
// 정규식 패턴에 매칭될 경우 true, 아닐 경우 false를 변수 IsValidCellPhone 에 저장한다.
또는 단순히 아래처럼 검사할 문자열과 정규표현식을 바로 넣어 확인할 수 있습니다.
print(("010-123-1234".range(of: #"^\(?\d{3,4}\)?[ -]?\d{3,4}[ -]?\d{4}$"# ,
options: .regularExpression)) != nil)
Foundation을 불러오지 않으면 아래와 같이, String의 range 멤버가 없고, regularExpression 멤버를 참조할 수 없다는 에러가 발생합니다.
3. 참고한/할 만한 링크
- 문자 및 부분 문자열 찾기
: 특정 문자, 문자열이 포함되어있는지를 확인할 수 있는 메서드를 문서 아랫쪽에서 확인할 수 있습니다.
https://developer.apple.com/documentation/foundation/nsstring/1416849-range
Apple Developer Documentation
developer.apple.com
- 스위프트 레퍼런스 매뉴얼의 패턴의 표현식 패턴 섹션 (Expression Pattern)
https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#ID426
Patterns — The Swift Programming Language (Swift 5.5)
Patterns A pattern represents the structure of a single value or a composite value. For example, the structure of a tuple (1, 2) is a comma-separated list of two elements. Because patterns represent the structure of a value rather than any one particular v
docs.swift.org
- 스위프트 랭귀지 가이드 : 문자열과 캐릭터
https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
Strings and Characters — The Swift Programming Language (Swift 5.5)
Strings and Characters A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values. Swi
docs.swift.org
- 애플개발자 사이트
https://developer.apple.com/documentation/foundation/nsstring/1416849-range
Apple Developer Documentation
developer.apple.com
- 스위프트에서 정규식 표현 사용하기 (advanced swift)
https://www.advancedswift.com/regular-expressions/#phone-number-regular-expression
Regular Expressions in Swift
Learn how to create and use regular expressions in Swift to validate emails, phone numbers, usernames, passwords, and dates.
www.advancedswift.com
- 스위프트에서 정규식 표현 사용하기 (티스토리)
https://tngusmiso.tistory.com/62
[Swift] 코딩테스트 보다가 열 받아서 정리하는 Swift 정규식 - NSRegularExpression (Regex)
문자열 문제 진짜 어렵다!!!!!!!!! 매번 구글링 하지 말고 정리해 둬야 겠다는 필요성을 느꼈다... Swift 주의사항 문자열에서 역슬래쉬( \ )는 연산자 역할을 하므로, \ 를 문자 자체로 사용하고 싶은
tngusmiso.tistory.com
마치며
오늘도 읽어주셔서 감사합니다.
궁금한 점이 있다면 댓글로, 도움이 되셨다면 공감 부탁드립니다.
혹시 수정하거나 피드백하실 내용 있다면 언제든 댓글로 부탁드립니다.
감사합니다.
'💻 Programming 개발 > 🍎 iOS 개발, Swift' 카테고리의 다른 글
[Swift][번역] 스위프트의 자료구조와 알고리즘 - 섹션 0. 시작하기 전에 (1) | 2022.05.13 |
---|---|
[Swift] 사용자 컬러셋 추가하고 UI Color 확장하여 코드로 접근하게 만들기 (0) | 2022.04.04 |
[Swift] 외부 라이브러리를 이용하기 위한 Cocoapods 설치 및 설정 + 설치과정에 오류가 생길 경우 (0) | 2022.03.28 |
[Swift]다양한 디바이스에 맞춰 셀 사이즈를 조정하고자 할 때 + 사이즈가 안 바뀌었을 때 해결방법 (CollectionViewDelegateFlowLayout 프로토콜) (0) | 2022.03.17 |
[Swift] 흐름제어구문 (0) | 2022.01.18 |
댓글