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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With