How to match a string not containing a substring using RegEx in Swift

1 Answer

0 votes
import Foundation

// ^: Matches the beginning of the string
// (?!notype): asserts that the current position in the string is not followed by the 
//             substring "notype"
// .: Matches any single character (except newline characters)
// *: Matches the preceding group (((?!notype).)) zero or more times
// $: Matches the end of the string

func stringNotContainingSubstring(_ pattern: String, _ text: String) -> Bool {
    let re = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
    let matches = re.firstMatch(in: text, options: [], range: NSRange(location: 0, length: text.count))
    
    return matches != nil
}

let pattern = "^((?!notype).)*$"

print(stringNotContainingSubstring(pattern, " notype"))
print(stringNotContainingSubstring(pattern, "notype "))
print(stringNotContainingSubstring(pattern, "notypevar"))
print(stringNotContainingSubstring(pattern, "anotypevar"))
print(stringNotContainingSubstring(pattern, "anotype"))
print(stringNotContainingSubstring(pattern, "The only approval you need is your own"))
print(stringNotContainingSubstring(pattern, "follow your dreams"))
print(stringNotContainingSubstring(pattern, "Never regret anything that made you smile"))
print(stringNotContainingSubstring(pattern, "A programming language"))



/*
run:
     
false
false
false
false
false
true
true
true
true
     
*/

 



answered Feb 28, 2025 by avibootz
edited Feb 28, 2025 by avibootz

Related questions

...