例如,如果我想匹配ips,可以将其分解为:
const octet = /\d{1,3}/;
const ip = /{octet}\.{octet}\.{octet}\.{octet}/;
Run Code Online (Sandbox Code Playgroud)
您可以将using new RegExp()和template文字混合使用,以达到类似目的。
下面是一个例子。
const octet = /\d{1,3}/;
const octetS = octet.source;
const ip = new RegExp(
`^${octetS}\\.${octetS}\\.${octetS}\\.${octetS}$`);
const ips = [
'127.0.0.1',
'10.0.2',
'12.10.2.5',
'12'];
for (const checkip of ips)
console.log(`IP: ${checkip} = ${ip.test(checkip)}`);Run Code Online (Sandbox Code Playgroud)
With an already declared regular expression literal, you can use its source property to get the version without the enclosing tags. Using template literals inside a new RegExp constructor, create your new expression.
const octet = /\d{1,3}/;
const octetSource = octet.source;
const ip = new RegExp(`^${octetSource}\\.${octetSource}\\.${octetSource}\\.${octetSource}$`);
Run Code Online (Sandbox Code Playgroud)