正则表达式:使用交替运算符组合模式或多次执行正则表达式
RegExp: combine patterns using alternation operator or execute regular expression several times
我需要一个字符串来匹配几种模式之一。什么被认为是更好的做法?在交替运算符的帮助下组合模式 |
:
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);
相关文章:
- _water_glass的javascript正则表达式模式
- 需要正则表达式模式的帮助
- 正则表达式模式与各种端点匹配
- JavaScript 中 URL 的正则表达式模式
- Java 与 Javascript 中的正则表达式模式
- 将Javascript正则表达式模式转换为C++std::regex的规则
- 如何从字符串构造正则表达式模式
- 城市和州正则表达式模式
- 如何在字符串上组合JS replace()方法中的3个正则表达式模式
- JavaScript中的递归正则表达式模式
- 正则表达式模式匹配特定单词
- 什么正则表达式模式将从包含的外部HTML文本中提取内部HTML
- 将特定的正则表达式模式与我的字符串匹配
- 为电子邮件开发正则表达式模式
- 将HTML5正则表达式模式转换为JavaScript正则表达式
- 我的正则表达式模式不起作用
- 将字符串中的正则表达式模式替换为依赖于匹配项的替换字符串
- 数字、字母块的正则表达式模式匹配
- Q>javascript 正则表达式模式
- 验证字符串是否为正则表达式模式的开头