user8597012
user8597012

Reputation: 43

Regex for repeating pattern

I need a regex which satisfies the following conditions. 1. Total length of string 300 characters. 2. Should start with &,-,/,# only followed by 3 or 4 alphanumeric characters 3. This above pattern can be in continuous string upto 300 characters

String example - &ACK2-ASD3#RERT...

I have tried repeating the group but unsuccessful.

(^[&//-#][A-Za-z0-9]{3,4})+ 

That is not working ..just matches the first set

Upvotes: 3

Views: 895

Answers (3)

Grillparzer
Grillparzer

Reputation: 417

You're close. Add the lookahead: (?=.{0,300}$) to the start to make it satisfy the length requirement and do it with pure RegExp:

/(?=.{0,300}$)^([&\-#][A-Za-z0-9]{3,4})+$/.test("&ACK2-ASD3#RERT")

Upvotes: 2

MH2K9
MH2K9

Reputation: 12039

You can try the following regex.

const regex = /^([&\/\-#][A-Za-z0-9]{3,4}){0,300}$/g;
const str = `&ACK2-ASD3#RERT`;
if (regex.test(str)) {
    console.log("Match");
}

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You may validate the string first using /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/ regex and checking the string length (using s.length <= 300) and then return all matches with a part of the validation regex:

var s = "&ACK2-ASD3#RERT";
var val_rx = /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/;
if (val_rx.test(s) && s.length <= 300) {
  console.log(s.match(/[&\/#-][A-Za-z0-9]{3,4}/g));
}

Regex details

  • ^ - start of string
  • (?:[&\/#-][A-Za-z0-9]{3,4})+ - 1 or more occurrences of:
    • [&\/#-] - &, /, # or -
    • [A-Za-z0-9]{3,4} - three or four alphanumeric chars
  • $ - end of string.

See the regex demo.

Note the absence of g modifier with the validation regex used with RegExp#test and it must be present in the extraction regex (as we need to check the string only once, but extract multiple occurrences).

Upvotes: 4

Related Questions