Home > Software engineering >  How do I combine these three regex into one?
How do I combine these three regex into one?

Time:05-27

I'm trying to make a regular expression that only accepts:

Min 100 and atleast 1000 characters, characters “,’,<,> aren't allowed, two full stops one after another aren't allowed.

This is what I have for now:

  • ^.{100,1000}$ → for 100 to 1000 characters
  • ^[^"'<>]*$ → for the characters that aren't allowed
  • ^([^._]|[.](?=[^.]|$)|_(?=[^_]|$))*$ → doesn't allow 2 consecutive dots

How do I combine this regex into one? ._.

CodePudding user response:

This part [^._] means no dot or underscore and this part [.](?=[^.]|$)|_(?=[^_]|$) matches either a . or _ followed by the opposite or end of string.

You could write the pattern using a single negative lookahead assertion excluding __ or ..

^(?!.*([._])\1)[^"'<>\n]{100,1000}$

Explanation

  • ^ Start of string
  • (?! Negative lookahead, assert that what is at the right is not
    • .*([._])\1 capture either . or _ and match the same captured char after it (meaning no occurrence of .. or __)
  • ) Close lookahead
  • [^"'<>\n]{100,1000} Match 100-1000 times any character except the listed
  • $ End of string

Regex demo (with the quantifier set to {10,100} for the demo)

  • Related