Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 728
user8597012 Avatar asked Jun 03 '26 01:06

user8597012


1 Answers

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).

like image 171
Wiktor Stribiżew Avatar answered Jun 05 '26 01:06

Wiktor Stribiżew