3

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.