I know that the regexp OR (|) operator in javascript matches if one of the sub-strings on both sides of the regexp is matched.
I also know that in JavaScript the logical (||) OR operator checks the second operand only if the first operand is false.
So I want to know if the regexp (|) (also called pipe) OR operator works the same way or it first matches both the sub-strings and then decide the match. If I am not wrong I think it should check the second right hand sub-string only when left hand sub-string is not matched for the sake of performance.
I know that the regexp OR (|) operator in javascript matches if one of the sub-strings on both sides of the regexp is matched.
I also know that in JavaScript the logical (||) OR operator checks the second operand only if the first operand is false.
So I want to know if the regexp (|) (also called pipe) OR operator works the same way or it first matches both the sub-strings and then decide the match. If I am not wrong I think it should check the second right hand sub-string only when left hand sub-string is not matched for the sake of performance.
Share Improve this question asked Nov 26, 2012 at 6:39 me_digvijayme_digvijay 5,50210 gold badges51 silver badges86 bronze badges 2- I'm sure it works in a similar fashion...it's called short-circuiting by the way. Is there any specific reason you want to know? Or is this just a general question? – Ian Commented Nov 26, 2012 at 6:46
- @Ian: I was working with the javascript regexp and when I encountered the OR operator, I thought that with logical operators its very simple to implement the so called short-circuiting, but with regexp, I think there must be some performance or memory cost to implement the same. – me_digvijay Commented Nov 26, 2012 at 6:50
1 Answer
Reset to default 8Yes, |
in regular expressions is short circuiting.
For example,
"The | is short circuiting, NOT!".match(/The \| is short circuiting(?:|, NOT!)/)
produces
["The | is short circuiting"]
while
"The | is not short circuiting, NOT!".match(/The \| is not short circuiting(?:, NOT!|)/)
produces
["The | is not short circuiting, NOT!"]
The language specification says
The production Disjunction :: Alternative
|
Disjunction evaluates as follows:
- Evaluate Alternative to obtain a Matcher m1.
- Evaluate Disjunction to obtain a Matcher m2.
- Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and performs the following:
a. Call m1(x, c) and let r be its result.
b. If r isn't failure, return r.
c. Call m2(x, c) and return its result.
15.10.2.3 line 3b is where the short-circuiting is specified.