0

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?

4
  • you need to add all the alternatives. Commented Feb 17, 2015 at 17:53
  • So something like "^\\s*H|He|Hel|Hell|Hello" you mean? Commented Feb 17, 2015 at 17:54
  • yep, like that. But use word boundaries also. Commented Feb 17, 2015 at 17:59
  • Maybe, This library helps you: github.com/pieceofsummer/WTReTextField Commented Feb 17, 2015 at 18:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That works great thank you! Could you explain a little about how the part in the bracket works?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.