Home > Blockchain >  Combine two regular expressions
Combine two regular expressions

Time:01-03

I have two regular expressions

  1. That allows only alphanumeric characters, three types of special characters(@$&) and a maximum of 20 characters in a sentence

^[a-zA-Z0-9@$&]{1,20}$

  1. That allows only non-repetitive consecutive words in a sentence

^(?!.?(\b[a-zA-Z] \b)\s\1).$

I am looking for a single regular expression which would give both abilities.OR Can we combine these? Please help

CodePudding user response:

It appears that you want to allow numbers and special characters @$& to count as "words" in the second regex, while also limiting the number of characters to 20.

If you simply replace [a-zA-Z] in the second regex with [a-zA-Z0-9@$&], then \b would fail to identify a "word" boundary when one of @$& is on the boundary. Instead, use negative lookarounds to assert that non-spaces are not preceded or followed by a non-space:

^(?!.*((?<!\S)\S )\s\1(?!\S))[a-zA-Z0-9@$& ]{1,20}$

CodePudding user response:

Some things are easier implemented in the host language and not in a regular expression.

If you want both regex to match:

var regex1 = /^[a-zA-Z0-9@$&]{1,20}$/;
var regex2 = /^(?!.?(\b[a-zA-Z] \b)\s\1).$/;

var input = prompt();
if (regex1.test(input) && regex2.test(input)) {
  console.log("both regex matched");
} else {
  console.log("zero or only one regex matched: "   regex1.test(input)   " && "   regex2.test(input));
}

If you want at least one regex to match:

var regex1 = /^[a-zA-Z0-9@$&]{1,20}$/;
var regex2 = /^(?!.?(\b[a-zA-Z] \b)\s\1).$/;

var input = prompt();
if (regex1.test(input) || regex2.test(input)) {
  console.log("at least one regex matched: "   regex1.test(input)   " || "   regex2.test(input));
} else {
  console.log("no regex matched");
}

CodePudding user response:

Yes we can combine both regular expressions.

var regx_for_alpha_special = new RegExp(/--RegexCode--/);
var regx_for_consecutive = new RegExp(/--RegexCode--/);

hence, regex can be dynamically created. After creation:

"sampleString".replace(/--whatever it should do--/);

Then you can combine them normally, yes.

var finalRe = new RegExp(regx_for_alpha_special.source   "|"   regx_for_consecutive.source);
  • Related