Home > Enterprise >  ReGex for 2 or more consecutive letters/numbers
ReGex for 2 or more consecutive letters/numbers

Time:06-12

I am trying to complete a regex where:

  1. only 2 consecutive white spaces/hyphens/commas/dots/slashes are allowed.
  2. maximum of 5 digits (consecutive or non-consecutive ) are allowed.
  3. 3 or more consecutive letters are not allowed.

I have tried the below regex, it worked well for the first 2 points, still need to achieve the third point.

^(?=.{3,50}$)(?!.*(((\d{6}))|( {2})|(-{2})|(,{2})|(\.{2})|(\/{2})))([a-zA-Z0-9 \-,.\/]) $

I am using this regex to validate the address input from the user, I will be glad to modify it if there are any improvements or suggestions.

Time Square, Main Road, 2279 allowed
Time-Square, Main Road-2279 allowed
Time Square Main Road NOT allowed "double spaces"
Time Square, Main Road, 22798741313 NOT allowed
Time Square, Main Road.. NOT allowed
Time Square, Main Road// NOT allowed
Time Square Main Road,, NOT allowed
Time Square Main Road-- NOT allowed
------- NOT allowed
--// NOT allowed
--/ NOT allowed
ttttttttttttttttttttttttttt NOT allowed
-/- NOT allowed
-/- NOT allowed
.,. NOT allowed
,-, NOT allowed
/-/-/-/- NOT allowed

CodePudding user response:

You may use this regex with negative lookahead conditions:

^(?!.*  )(?!.*[-,/.]{2})(?!.*(?:[^\d\n]*\d){6})(?!.*([a-zA-Z])\1\1).{3,50}$

RegEx Demo

Explanation:

  • ^: Start
  • (?!.* ): Don't allow 2 consecutive spaces
  • (?!.*[-,/.]{2}): Don't allow repeat of these special characters
  • (?!.*(?:[^\d\n]*\d){6}): Don't allow more than 5 digits
  • (?!.*([a-zA-Z])\1\1): Don't allow 3 consecutive repeat of same letter
  • .{3,50}: Match 3 to 50 of any characters
  • $: End
  • Related