What’s the difference between this regex: /(everything|cool)/gi and this one: /(?:everything|cool)/gi ?
I’m asking this because I’ve got an regex which I wasn’t able to write myself* and there are, as you can see below, a lot of ?: in that regex. I’ve read somewhere that ?: is bad for performance so I want to remove it.Can I remove it or is it important for anything?
* (?:(?=(?:(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*'(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*')*(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*$)(?=(?:(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*"(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*")*(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*$)(?:\\.|[^\\'"]))+
Without
?:, a reference to a matched group is created.With a
?:, the group is matched, but not captured.Here’s a benchmark on both methods: http://jsperf.com/regex-capture-vs-non-capture
By looking at the bars, one would say that the non-captured groups are faster. However, if you look at the bottom, the differences can be neglected, since both methods are already incredibly fast.
Removing or adding
?:to an existing solution might break the code, so I advise to not edit the RegExp when it’s not causing any issues.