1

I am trying to construct a regular expression with the following requirements

  1. Pattern should start with letters a-z
  2. Can have any character from character class [\w:-].
  3. Can have any number of underscores _ but only if there is a : somewhere before it in the pattern.

Some examples of valid patters

hello123

hello:123

hello-hello

hello:123-hello_345 # Valid pattern as there is a : in the pattern before _

hello-1:hell_world_123

Invalid patterns

hello_123

hello-123_world

hello_123:world

I have tried using the lookaheads but for some reason it does not work, below is the pattern i came up with

^[a-z]+[a-z0-9:-]*(?<=:)[_]*\w* - the issue with this pattern is that it stops matching the entire pattern if there is no : anywhere in the string, so it kind of makes the : a required pattern.

I only want to check the existence of : if there is _ anywhere in the string before :.

1
  • A positive lookahead requires the presence of some pattern, so it is expected to stop working if the positive lookahead pattern does not match. You need a negative lookahead in these cases. See my answer below. Commented Aug 7, 2019 at 8:38

3 Answers 3

1

You may use

^(?![^_:]*_)[a-z][\w:-]*$

The (?![^_:]*_) negative lookahead fails the match if there is _ that is not preceded with _ and :.

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • (?![^_:]*_) - a negative lookahead that fails the match if there are 0+ chars other than _ and : followed with _ immediately to the right of the current location
  • [a-z] - a lowercase ASCII letter
  • [\w:-]* - 0+ word, : or - chars
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

Comments

0

It can be solved with the "or" operator :

^[a-z]+[a-z0-9-]*(:[a-z0-9-_]*|[a-z0-9-]*)$

It has the advantage to be KISS.

Comments

0

^[a-z]+[a-z0-9-]*((:.+)|(:[a-z0-9-_]*)|[a-z0-9-]*)$ So, it can be solved by adding pattern groups in OR clauses. This one does work for the examples you gave. You can add if there are any groups which aren't captured.

Hope it helps!

Comments

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.