Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check is there any consecutive characters with a regex in Swift 4.0?

Tags:

regex

ios

swift

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 and aa

Thanks

like image 558
AykutE Avatar asked Oct 28 '25 19:10

AykutE


2 Answers

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

enter image description here

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:

enter image description here

like image 61
Krunal Avatar answered Oct 30 '25 10:10

Krunal


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)
    }
like image 36
Reinier Melian Avatar answered Oct 30 '25 09:10

Reinier Melian