Lazarev Alexandr Lazarev Alexandr - 4 months ago 9
Javascript Question

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

I need a string to match one of the several patterns. What is considered to be a better practice? Combine patterns with the help of alternation operator

|
:

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


Or to execute regular expression several times with different patterns:

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


The thing I like, when executing regular expression several times is that resulted array will always have the same structure, while using combined pattern the result would be different for matching height and width because width will match first two capturing parenthesis, but height the last two.

For example if string is
width-20
the result would be:

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


And for
height-20
:

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


But what is a better way from performance point of view?

Answer

First I thought the first option was faster but after some Testing at 1E6 iterations I reached the Conclusion that using OR in RegExp is slower ~30-40%

was able to solve 1 million iteration in 75-99ms

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

was able to solve 1 million iteration in 120-140ms

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

EDIT

using the Third option prived by @nnnnnn :

was able to solve 1 million iteration in 110-125ms

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