Swift

Introduction to Regular Expressions

I’m been working in an application that need to use Regular Expression (as well known as Regex) to validate user informations so today I want to talk a little bit about it. Let’s get started.

Regular Expressions

Regular Expressions are useful for parsing and validating if any text matches a given pattern or not. Let’s say if you’re building a login screen and you want to enable the login button when and only when the user type a correct email form you can use regex to help you very easily.

Swift provides us an API to play around with regex that is: NSPredicate. You can define it like this:

let input = "hello world"
let pattern = // we'll learn very soon
let regex = NSPredicate(format: "SELF MATCHES %@", pattern)
let isMatches = regex.evaluate(with: input) // returns bool

Pretty straightforward if your input is matches the a given pattern isMatches returns true, otherwise returns false. Now we gonna learn how to define a pattern.

Patterns by examples

  1. Matches any string that has world in it. Try it
let pattern = world

2. Matches any string that starts with world. Try it

let pattern = ^world

3. Matches any string that ends with world. Try it

let pattern = world$

4. Matches any string that starts and ends with world. Try it

let pattern = ^world$

5. Matches a string that has cha followed by zero or more o. Try it

let pattern = chao*

6. Matches a string that has cha followed by one or more o. Try it

let pattern = chao+

7. Matches a string that has cha followed by zero or one o. Try it

let pattern = chao?

8. Similar to 5. Matches a string that has ch followed by zero or more ao .Try it

let pattern = ch(ao)*

9. Matches a string that has cha followed by two o. Try it

let pattern = chao{2}

10. Matches a string that has cha followed by two to five o. Try it

let pattern = chao{2,5}

11. Matches a string that has cha followed by two or more o. Try it

let pattern = chao{2,}

12. Matches a string that has either an a or a t or a a . Try it

let pattern1 = [ota]
let pattern2 = (o|t|a)

13. Matches a string that contains characters from a to z or A to Z. Try it

let pattern = [a-zA-Z]

14. Matches a string that contains a character from a to z or A to Z before vietnam . Try it

let pattern = [a-zA-Z]vietnam

15. Matches a string that does not start with a character from a to z or A to Z. Try it

let pattern = [^a-zA-Z]

Summary

That’s a lot and there’s still more but in this article I just cover the basics. Try to practice all of them. OK, Combine it all together let try to solve problem I mentioned in the Regular Expressions section above.

Here’s result:

let pattern = [A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,64}

Thanks for reading. Don’t forget to share and comment your thoughts in the comment section bellow.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *