Can anyone give me a Swift regex to identify consecutive characters in a string?
My regex is .*(.)\\\\1$
and this is not working. My code block is;
let regex = ".*(.)\\1$"
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: string)
Examples:
abc123abc -> should be valid
abc11qwe or aa12345 -> should not be valid because of
11
andaa
Thanks
This regex may help you, (Identifies consecutive repeating characters - It validates and satisfies matches with samples you've shared. But you need to test other possible scenarios for input string.)
(.)\\1
Try this and see:
let string = "aabc1123abc"
//let string = "abc123abc"
let regex = "(.)\\1"
if let range = string.range(of: regex, options: .regularExpression) {
print("range - \(range)")
}
// or
if string.range(of: regex, options: .regularExpression) != nil {
print("found consecutive characters")
}
Result:
Use NSRegularExpression
instead of NSPredicate
let arrayOfStrings = ["abc11qwe","asdfghjk"]
for string in arrayOfStrings {
var result = false
do{
let regex = try NSRegularExpression(pattern: "(.)\\1", options:[.dotMatchesLineSeparators]).firstMatch(in: string, range: NSMakeRange(0,string.utf16.count))
if((regex) != nil){
result = true
}
}
catch {
}
debugPrint(result)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.