2

I'm implementing validation for username field using Regular Expression(Regex) in iOS. I don't want username to start with the word "guest". I tried below code but it's not working.

[txtUserName addRegx:@"^(guest)" withMsg:@"Username Can't start with the word guest"];

Ideas?

alexandresaiz
  • 2,678
  • 7
  • 29
  • 40
Mughees Musaddiq
  • 1,060
  • 1
  • 10
  • 27

2 Answers2

2

You can try to use this Regex:

^(?!guest).*$

Explanation:

^ assert position at start of the string

(?!guest) Negative Lookahead - Assert that it is impossible to match the regex below guest matches the characters guest literally (case sensitive)

.* matches any character (except newline)

Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

$ assert position at end of the string

EDIT:

To make it case insensitive you can try this:

^(?i:(?!guest)).*$
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You have to remove the ( ) like the following:

[txtUserName addRegx:@"^guest" withMsg:@"Username Can't start with the word guest"];
realtimez
  • 2,525
  • 2
  • 20
  • 24
  • Thanks but it accepts guest as a first word of user name and I want exactly opposite of it. I don't want username textField to accept "guest" as a first word. Any suggestions? – Mughees Musaddiq Sep 04 '15 at 11:15