BenJacob
BenJacob

Reputation: 987

How to match regular expression up to end of string?

I am trying to use regular expressions to check user input as they type. For example if I wanted to check against the string "Hello", and the user input was "H", "He", ..., "Hello" "Hello world" etc. it would be valid but "Hi", "H e" etc. would not.

I am currently using:

if let range = s.rangeOfString("^\\s*Hello", options: .RegularExpressionSearch){
    //Valid
}

But this does not accept "H", "He", etc. Is there a way to do this using regular expressions?

Upvotes: 0

Views: 125

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to add all the alternatives like below.

^\\s*H(?:ello|el?l?)?\\b

Note that ? repeats the previous token zero or 1 time. Don't consider the ? present inside lookarounds (?<=..) , (?=..) or non-capturing group (?:..). | called alternation operator. It will use the pattern on it's left side first. If this pattern finds a match then it won't touch the pattern which was present to it's right side. So H(?:ello)\\b matches Hello and He matches He, since we made the l present in the 2nd pattern as optional. Likewise it goes on. ? after the non-capturing group will make the whole group as optional one. So now we get a pattern like ^\\s*H\\b, now this matches a single H.

Upvotes: 1

Related Questions