4

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

Community
  • 1
  • 1
AykutE
  • 344
  • 3
  • 15
  • `.*(.)\\1$` will only get repeated characters at the end of a string because you anchored it with `$`. You haven't given us sample strings so there isn't much we can say as to why this isn't working since we don't have sample input to test against. Are you simply checking whether or not a single repeated character exists? – ctwheels Apr 10 '18 at 13:50
  • @ctwheels, i edit the question and add some examples. Thanks – AykutE Apr 10 '18 at 13:55
  • 1
    `"(.)\\1"` should be sufficient. – sshine Apr 10 '18 at 13:55
  • 1
    @aykutt you can simply use `(.)\\1`. Is this for password validation by chance? – ctwheels Apr 10 '18 at 13:56
  • Thanks @ctwheels, yes it is for password validation – AykutE Apr 10 '18 at 14:09
  • 1
    If you want to use `NSPredicate` with `MATCHES` you need `let regex = ".*(.)\\1.*$"`, but it is very inefficient. – Wiktor Stribiżew Apr 10 '18 at 14:11
  • 1
    @aykutt this may help you then: [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/) – ctwheels Apr 10 '18 at 14:14
  • You don't need a regex to check for repeated characters ... – Martin R Apr 10 '18 at 14:20
  • If you really want to use a regex, you'd better use partial matching, something like `if let range = str.range(of: "(.)\\1", options: .regularExpression) { ... }` – Wiktor Stribiżew Apr 10 '18 at 14:27

2 Answers2

5

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

Krunal
  • 77,632
  • 48
  • 245
  • 261
2

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)
    }
Reinier Melian
  • 20,519
  • 3
  • 38
  • 55