-1

I need to create an expression that fit this requirements :

  • The string must be composed by 3 substring

  • The first substring accept 0-9a-zA-Z, the minimum length is 1 and there is notte max length

  • The second substring must be " - "

  • The last have The first's one same condition

  • Total maximum string length must be 28 chars

It is possible to accomplish this requirement with Regex?

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Monica
  • 13
  • 1

1 Answers1

1

Following regex should work fine:

/(?=^.{3,28}$)[^\W_]+\-[^\W_]+/

var array = [
  "123456790-123456789012345678",
  "123456790-1234567890123456789",
  "adsd-dsds"
];
var re = /(?=^.{3,28}$)[^\W_]+\-[^\W_]+/;
array.forEach(e => console.log(re.test(e) ? e.match(re)[0]: "match failed"));

Breakdown shamelessly copied from regex101.com:

  • Positive Lookahead (?=^.{3,28}$)
    • ^ asserts position at start of a line
    • .{3,28} matches any character (except for line terminators)
    • {3,28} Quantifier — Matches between 3 and 28 times, as many times as possible, giving back as needed (greedy)
    • $ asserts position at the end of a line
  • Match a single character not present in the list below [^\W_]+
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    • \W matches any non-word character (equal to [^a-zA-Z0-9_])
    • _ matches the character _ literally (case sensitive)
    • \- matches the character - literally (case sensitive)
  • Match a single character not present in the list below [^\W_]+
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    • \W matches any non-word character (equal to [^a-zA-Z0-9_])
    • _ matches the character _ literally (case sensitive)
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • Thanks Aniket !!!!!!! It works fine !!!!!! – Monica Apr 14 '18 at 18:34
  • @Monica Do not use `[A-z]` to match all ASCII letters, use `[A-Za-z]`. See [Why is this regex allowing a caret?](https://stackoverflow.com/questions/29771901/why-is-this-regex-allowing-a-caret/29771926#29771926) – Wiktor Stribiżew Apr 14 '18 at 19:25