- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if string contains special characters in Swift
To check if a string contains a special character in swift we can use conditionals like if else or switch but that would need a lot of conditions to be executed, making programming as well as execution time consuming. So in this example we’ll see how to do the same task with regular expressions and another method that swift provides to check if some character exists in a character set.
Method 1 − Using regular expression
Let’s create an extension of String and add the following code into that
extension String { var containsSpecialCharacter: Bool { let regex = ".*[^A-Za-z0-9].*" let testString = NSPredicate(format:"SELF MATCHES %@", regex) return testString.evaluate(with: self) } }
We can run the following code as an example shown below.
override func viewDidLoad() { super.viewDidLoad() print("3r42323".containsSpecialCharacter) print("!--%332".containsSpecialCharacter) }
Output
Here is the result for method 1
Now we’ll see the same example with method 2.
Method 2
let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) if "3r42323".rangeOfCharacter(from: characterset.inverted) != nil { print("true") } else { print("false") } if "!--%332".rangeOfCharacter(from: characterset.inverted) != nil { print("true") } else { print("false") }
Output
The result produced is shown below.
- Related Articles
- Check if string contains another string in Swift
- MySQL search if more than one string contains special characters?\n
- Program to check if a string contains any special character in C
- Program to check if a string contains any special character in Python
- C# program to check if a string contains any special character
- Java program to check if a string contains any special character
- How to check if a string contains only decimal characters?
- How to check if a string only contains certain characters in Python?
- Java Program to check if the String contains only certain characters
- Python program to check if a string contains all unique characters
- How to check if a unicode string contains only numeric characters in Python?
- Python Program to check if String contains only Defined Characters using Regex
- Check whether the String contains only digit characters in Java
- Java Program to check if the String contains any character in the given set of characters
- Check if a string contains numbers in MySQL?

Advertisements