Regex to not allow staring whitespace in string swift ios

Viewed 647

I want to create regex thats allows characters numbers and spaces but not at the begning of string , i have created below one but its not working "^\\S.*[^A-Za-z0-9_ ].*".

Swift:

func containsAllowedCharacters(regex: String?, stringToCheck: String) -> Bool {
    var isValid = false
    if let regex = regex {
        let testString = NSPredicate(format: "SELF MATCHES %@", regex)
        isValid = testString.evaluate(with: stringToCheck)
    }
    return !isValid
}
2 Answers

You are looking for lookaheads:

^(?! )[ \w]+$

\w is a short form for [\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\u200c\u200d] (see here and here for more information) as it is used very often, but see @Wiktor's comment for a more precise clarification.

Also,see a demo on regex101.com.

Your pattern, ^\S.*[^A-Za-z0-9_ ].*, matches start of string with ^, then matches any non-whitespace char with \S (note it matches any punctuation, letters and digits), then matches any zero or more chars other than line break chars as many as possbile with .*, then matches any char other than an ASCII letter, digit, _ or space, and then again matches any zero or more chars other than line break chars as many as possbile with .*.

As you see, all the pattern parts match more than you allow. Also, pay attention you actually require at least two chars to be present with this pattern while your code implies you need to support zero length string, too.

You can use

let FileNameRegex = #"^(?!\s)[A-Za-z0-9_\s]*$"#

NOTE: As you are using it with MATCHES in the NSPredicate.evaluate, you do not need the ^ and $ anchors on both ends since MATCHES requires a full string match:

let FileNameRegex = #"(?!\s)[A-Za-z0-9_\s]*"#
let testString = NSPredicate(format: "SELF MATCHES %@", regex)

Note the use of #"..."# notation that makes a raw string literal, where a single backslash is parsed as a literal backslash.

The pattern matches

  • ^ - start of string
  • (?!\s) - a negative lookahead that matches a location in string that is not immediately followed with a whitespace
  • [A-Za-z0-9_\s]* - zero or more (due to the * quantifier) ASCII letters, digits, underscores and whitespaces
  • $ - end of string.
Related