正则表达式:使用交替运算符组合模式或多次执行正则表达式

RegExp: combine patterns using alternation operator or execute regular expression several times

本文关键字:正则表达式 模式 执行 组合 运算符      更新时间:2023-09-26

我需要一个字符串来匹配几种模式之一。什么被认为是更好的做法?在交替运算符的帮助下组合模式 |

const regexp = /(width)-('d+)$|(height)-('d+)$/
const matches = regexp.exec(string);

或者使用不同的模式多次执行正则表达式:

const regexp = /(width)-('d+)$/
const regexp2 = /(height)-('d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);
我喜欢的事情是,当多次

执行正则表达式时,结果数组将始终具有相同的结构,而使用组合模式时,匹配高度和宽度的结果会有所不同,因为宽度匹配前两个捕获括号,但高度是最后两个。

例如,如果字符串width-20则结果为:

[ 'width-20',
  'width',
  '20',
  undefined,
  undefined,
  index: 0,
  input: 'width-20' 
]

对于height-20

[ 'height-20',
  undefined,
  undefined,
  'height',
  '20',
  index: 0,
  input: 'height-20' 
]

但是,从性能的角度来看,还有什么更好的方法呢?

首先,我认为第一个选项更快,但经过1E6次迭代的一些测试,我得出的结论是在正则表达式中使用OR更慢~30-40%

能够在75-99ms内解决100万次迭代

const regexp = /(width)-('d+)$/
const regexp2 = /(height)-('d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);

能够在120-140ms内解决100万次迭代

const regexp = /(width)-('d+)$|(height)-('d+)$/
const matches = regexp.exec(string);

编辑

使用@nnnnnn授予的第三个选项:

能够在110-125ms内解决100万次迭代

const regexp = /(width|height)-('d+)$/
const matches = regexp.exec(string);