Home > Software engineering >  Check string matches exact format swift 5
Check string matches exact format swift 5

Time:12-04

I want to check if a string matches an exact regex pattern;

Currently, even though the string being compared is not an exact match, my function is returning true.

Pattern String: "([0-9],[0-9])"

For example,

(1,1) is valid

(5,4) is valid

Only strings entered in this format are valid I.E. Bracket Number Comma Number Bracket (Without spaces)

I.E.

[5,5] is not valid

{5,5] is not valid.

5,5 is not valid

Code I am using to check:

let stringToCheck = "[5,5]"

return stringToCheck.range(of: "([0-9],[0-9])", options: .regularExpression, range: nil, locale: nil) != nil

Can anyone help me with how to adjust this to check for exact matches in line with my pattern?

Thanks!

CodePudding user response:

You need two things:

  • Escape parentheses
  • Add anchors because in the current code, the regex can match a part of a string.

You can thus use

stringToCheck.range(of: #"^\([0-9],[0-9]\)\z"#, options: .regularExpression, range: nil, locale: nil) != nil

Note the # chars on both ends, they allow escaping with single backslashes.

Details:

  • ^ - start of string
  • \( - a ( char
  • [0-9] - a single ASCII digit (add after ] to match one or more digits)
  • , - a comma
  • [0-9] - a single ASCII digit (add after ] to match one or more digits)
  • \) - a ) char
  • \z - the very end of string (if linebreaks cannot be present in the string, $ is enough).
  • Related