0

I got a Regex from an API. I need to validate the regex if it is valid or not.

This is a sample regex pattern:

/^[a-z0-9_-]{6,18}$/

I need to validate this string.

Edit: I have tried initwithpattern with a invalid regex [, But its not throwing any error.

Muruganandham K
  • 5,271
  • 5
  • 34
  • 62
  • 1
    validating the regex means that you want to apply it or check if it's a valid regex? – Ahmad F Oct 03 '17 at 12:05
  • show your tried code – Anbu.Karthik Oct 03 '17 at 12:05
  • 2
    Agreed with @AhmadF. For the last one: https://stackoverflow.com/questions/32743099/validate-regex-in-swift for the first one: https://stackoverflow.com/questions/29784447/swift-regex-does-a-string-match-a-pattern – Larme Oct 03 '17 at 12:06

1 Answers1

2

You should initialize an instance of NSRegularExpression with the given regex pattern and check whether that NSRegularExpression is NULL.

NSString *regexString = @"/^[a-z0-9_-]{6,18}$/";
NSError *error = NULL;
NSRegularExpression *regex = 
    [NSRegularExpression regularExpressionWithPattern:regexString 
                                              options:0 
                                                error:&error];

if (!regex) {
    //regex is invalid
}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • 5
    No. The *correct* way to check for failure or success of Cocoa methods is to check the *return value* (in this case for `NULL`). Compare https://stackoverflow.com/questions/29384218/swift-idiomatic-error-checking, which has a link to the Apple documentation. – Martin R Oct 03 '17 at 12:25
  • @MartinR Noted, this is some valuable piece of information. Edited my answer accordingly. – Tamás Sengel Oct 03 '17 at 12:29
  • i have tried [initwithpattern](https://developer.apple.com/documentation/foundation/nsregularexpression/1410900-initwithpattern) with a invalid regex. No luck. But this is working. – Muruganandham K Oct 03 '17 at 12:57
  • `[` isn't a valid regex. `[` is a special character. If you want to validate a string of type `[restOfMyString`, you need to escapde the `[` doing `\[`. Here is a great memo about regex, and showing the char to escape if needed: https://koenig-media.raywenderlich.com/downloads/RW-NSRegularExpression-Cheatsheet.pdf – Larme Oct 03 '17 at 13:07