0

My regex is a little rusty and I could use some help. I am writing a regex to use for validating a user id for a java application.

The two rules that the id has to meet:

  1. Must begin with a -, _, 0-9, a-z or A-Z.
  2. Not allowed to contain a %, backslash, +, /, #, ::, single quote, or double quote

The part I am having trouble with is the double colon. The id can contain a single colon but cannot contain one back to back.

This is what I have come up with but it does not seem to work.

^[a-zA-Z0-9\-_]([^%\+\\\/\#'\"]|^(?!::))+$

Any advice would be great.

2
  • it does not seem to work is not a problem statement. You need to elaborate on what exactly that means. Commented Nov 20, 2017 at 22:43
  • It can't work because ^(?!::) only fails the start of the string if it is followed with ::. Everywhere else, it does not match anything. Commented Nov 20, 2017 at 22:48

1 Answer 1

1

The (?!::) is a negative lookahead that only fails the match when there are two colons at the start of the string.

You may use a (?!.*::) negative lookahead right after matching the first char:

String rx = "^[a-zA-Z0-9_-](?!.*::)[^%+\\\\/#'\"]+$";

When using with matches(), you may omit the ^ and $ anchors.

See the regex demo

Details

  • ^ - string start (implicit in matches())
  • [a-zA-Z0-9_-] - a word or - char (thus, can be reduced to [\w-])
  • (?!.*::) - no :: after any 0+ chars other than line break chars
  • [^%+\\\\/#'\"]+ - 1 or more chars other than %, +, \, /, #, ' and "
  • $ - end of string (implicit in matches())
Sign up to request clarification or add additional context in comments.

3 Comments

For potential better performance, bullets 3 and 4 could be combined using | between valid chars excluding :, and a check for single :, e.g. (?:[^%+\\\\/#'\":]|:(?!:))+. This eliminates the backtracking that would otherwise be triggered by .*.
@Andreas I would unroll it then like "^[a-zA-Z0-9_-][^%+\\\\/#'\":]*(?::(?!:)[^%+\\\\/#'\":]*)*$" to eliminate the redundant backtracking caused by |.
Thanks this is exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.