2
votes

I am a little new to using regex. I am getting the following error:

The operation couldn’t be completed. (Cocoa error 2048.)

when trying to build the following regular expression with NSRegularExpression in Swift:

let regex = try NSRegularExpression(pattern: "^(?=.*[A-Z])(?=.*[a-z]).{7-15}$", options: .CaseInsensitive)

I am trying to validate the user input string to contain at least one upper case letter and at least one lower case letter while restricting the length of the string to between 7 and 15 characters. Thanks

2
Two things should be changed, I think: 1) fix the limiting quantifier from {7-15} to {7,15}, 2) Remove the .CaseInsensitive flag, replace with []. (if the [] is not accepted, try nil instead).Wiktor Stribiżew
Thanks, I see your point, I replaced the .CaseInsensitive flag with [ ].Jace

2 Answers

1
votes

Your pattern isn't totally correct. The length range syntax uses a comma:

"^(?=.*[A-Z])(?=.*[a-z]).{7,15}$"
1
votes

In order to valide the user input, use this regex :

^(?=.*[a-z])(?=.*[A-Z])(?=.{7})(?!.{16}).+$

^               // start of the string
(?=.*[a-z])     // assert that at least one lowercase exists
(?=.*[A-Z])     // assert that at least one uppercase exists
(?=.{7})        // assert that at least 7 characters exists
(?!.{16})       // assert that the string cannot exceed 15 characters (negative lookahead)
.+              // get the entire string
$               // end of the string

You can check the demo here.