Reputation: 2298
The following line is in the jQuery source code:
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
I am confused by the last vertical bar in the two non-capturing groups,
(?:\d*\.|)
and
(?:[eE][\-+]?\d+|)
The regular expression /(a|b)/ matches a or b, so I wondered what /(a|b|)/ matches, and it seems to "match everything", in other words
reg1 = /(a|b)/;
reg1.test('c'); // false
reg2 = /(a|b|)/;
reg2.test('c'); // true
What is going on?
Upvotes: 2
Views: 590
Reputation: 298136
I'll try to break this down into chunks:
[\-+]?
: This matches a plus sign, a minus sign or neither.(?:\d*\.|)
: This groups (the ?:
makes it a non-capturing group) any number of digits followed by a dot or nothing at all.\d+
: This matches one or more consecutive digits.(?:[eE][\-+]?\d+|)
: This groups a lowercase or uppercase "e", possibly followed by a plus or a minus and all of that followed by digits. Or, nothing.(a|)
looks for a
first. If a
doesn't exist, it matches nothing. It's a confusing way of writing (a)?
.
This regex is a little confusing. I'd re-write it like this:
/[+-]?\d*\.?\d+(?:e[+-]?\d+)?/i
Upvotes: 1
Reputation: 7470
[\-+]? # a plus or a minus sign (optional)
(?: # a non-capturing group
\d*\. # 0 or more decimals and a dot [cond-A1]
| # or
# nothing [cond-A2]
)
\d+ # 1 or more decimals [decimal]
(?: # a non-capturing group
[eE][\-+]?\d+ # (e or E) + optional(minus or plus) + 1 or more decimals [cond-B1]
| # or
# nothing [cond-B2]
)
Here are some examples (I'm skipping the first optional plus/minus signs).
[cond-A1][decimal][cond-B2]
[cond-A1][decimal][cond-B2]
[cond-A2][decimal][cond-B2]
[cond-A1][decimal][cond-B1]
[cond-A1][decimal][cond-B1]
Upvotes: 1
Reputation: 13450
(a|b|)
it is mean a
or b
or "nothing", 'c' contains "nothing"
Upvotes: 1