'Regular expression pipe confusion
How come this code returns true?
string to match: ab
pattern: /^a|b$/
but when I put parentheses like this:
pattern: /^(a|b)$/
it will then return false.
Solution 1:[1]
The first pattern without the parenthesis is equivalent to /(^a)|(b$)/.
The reason is, that the pipe operator ("alternation operator") has the lowest precedence of all regex operators: http://www.regular-expressions.info/alternation.html (Third paragraph below the first heading)
Solution 2:[2]
/^a|b$/ matches a string which begins with an a OR ends with a b. So it matches afoo, barb, a, b.
/^(a|b)$/ : Matches a string which begins and ends with an a or b. So it matches either an a or b and nothing else.
This happens because alteration | has very low precedence among regex operators.
Solution 3:[3]
The first means begin by an a or end with a b.
The second means 1 character, an a or a b.
Solution 4:[4]
In ^a|b$ you are matching for an a at the beginning or a b at the end.
In ^(a|b)$ you are matching for an a or a b being the only character (at beginning and end).
Solution 5:[5]
| has lower priority than the anchors, so you're saying either ^a or b$ (which is true) as opposed to the 2nd one which means "a single character string, either a or b" (which is false).
Solution 6:[6]
This is the simplest way to achieve exact match search for datatables.net It took almost 4 hours to find this
Use this line of code at your level then enough
$('#example').DataTable().column(1).search(val + "$", true, false, true).draw();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Community |
| Solution 3 | AProgrammer |
| Solution 4 | Cobra_Fast |
| Solution 5 | |
| Solution 6 | Suraj Rao |
