Skip to content
DeveloperMemos

Checking if a String Contains a Prefix in Swift

Swift, String1 min read

When working with strings in Swift, you may need to check whether a string contains a specific prefix. In this article, we will explore how to accomplish this task using built-in string functions and regular expressions.

Using hasPrefix Method

The String class in Swift has a convenient method called hasPrefix that checks whether the string starts with a given prefix. The method returns a Boolean value indicating whether the string has the prefix or not. Here’s an example:

1let str = "Hello, world!"
2if str.hasPrefix("Hello") {
3 print("String starts with Hello")
4} else {
5 print("String does not start with Hello")
6}

Output:

1String starts with Hello

In this example, we create a string str and check whether it starts with the prefix "Hello". Since it does, the output is "String starts with Hello".

Using Regular Expressions

Another way to check for a prefix in a string is to use regular expressions. Regular expressions provide a powerful and flexible way to match patterns in strings. In Swift, you can use the NSRegularExpression class from the Foundation framework to work with regular expressions.

Here’s an example of how to use regular expressions to check for a prefix in a string(don't forget to import Foundation):

1let str = "Hello, world!"
2let pattern = "^Hello"
3let regex = try! NSRegularExpression(pattern: pattern)
4let range = NSRange(location: 0, length: str.utf16.count)
5
6if regex.firstMatch(in: str, options: [], range: range) != nil {
7 print("String starts with Hello")
8} else {
9 print("String does not start with Hello")
10}

Output:

1String starts with Hello

In this example, we create a regular expression pattern that matches strings that start with "Hello" using the ^ symbol. We then create an NSRegularExpression object with the pattern and use the firstMatch(in:options:range:) method to search for a match in the string. If the method returns a non-nil result, we know that the string contains the prefix.

Conclusion

Checking for a prefix in a string is a common task in many Swift applications. In this article, we explored two ways to accomplish this task: using the hasPrefix method and regular expressions. By using these techniques, you can easily check whether a string has a given prefix and take appropriate action based on the result.