Home > Blockchain >  javascript regex for special condition
javascript regex for special condition

Time:01-31

I am trying to create regex for below condition:

Allowed characters: letters (a-z) (not case sensitive), min-length: 1, max-length: 255.

Numbers and Special Characters (except @,$,%,^) are only allowed in combination with words (a-z texts).

Consecutive special characters are not allowed.

Numbers (up to 4 together) and/or 1 special character can appear in combination with words.

Ex:

9900Acres

Grey Hound!

[Roy]Media

Cool,boy

are all allowed.

I can't seem to get the hang of it.

I tried creating this regex -

^(?:((([0-9]{0,4})[ ]{0,})([!#&*()<,>.?/{}\[\]_-]{0,1})([0-9]{0,4})[a-zA-Z]{1,255}(([0-9]{0,4})([ ]{0,})([0-9]{0,4}))([!#&*()<,>.?/{}\[\]_-]{0,1})) ){3,}$

but with no success

CodePudding user response:

challenge accepted:

instead of one mega-regex, break it down:

function isValid(text = '') {
  if (!text.length || text.length > 255) {
    return false;
  }

  // check if there are more than 4 consecutive numbers
  if (/[0-9]{5,}/.test(text)) {
    return false;
  }

  // check if there are 2 consecutive special characters
  if (/[!#&*()<,>.?/{}[\]_-]{2,}/.test(text)) {
    return false;
  }

  return true; // should be fine ?
}

console.log(isValid('9900Acres')); // true
console.log(isValid('Grey Hound!')); // true
console.log(isValid('[Roy]Media')); // true
console.log(isValid('Cool,boy')); // true

CodePudding user response:

Try with this:

^(?=.*[A-Za-z])(?!.*[^a-zA-Z\d\n]{2})(?!(?:.*[^\da-zA-Z\n])?\d (?:[^\da-zA-Z\n].*)?$)[ !#&*()<,>.?\/{}\[\]\w-]{1,255}$

Explained:

^ # Start of line / String
    
    # Lookahead: whatever   some letter
    (?=.*[A-Za-z])
    
    # negative lookahead: whatever   2 consecutive forbidden characters
    (?!.*[^a-zA-Z\d\n]{2})
    
    # negative lookahead to forbid numbers without letters on some of the sides:
    (?!
        (?:.*[^\da-zA-Z\n])?  # Optional: something   special character
        \d                    # numbers
        (?:[^\da-zA-Z\n].*)?$ # Optional: special character   something   end of string
    )

    # All allowed characters 1 to 255 times
    [ !#&*()<,>.?\/{}\[\]\w-]{1,255}
$ # End of line / string

You have a demo here

  •  Tags:  
  • Related