I am trying to write a regex that will match the following YACC expression:
[left | right] || [top | bottom]:
It should match: (left or right) AND OR (top or bottom). OR ‘|‘ is simple to do but ‘||‘ I can’t figure it out.
This expression is part of a CSS gradient grammar defined by W3C:
<linear-gradient> = linear-gradient(
[ [ <angle> | to <side-or-corner> ] ,]?
<color-stop>[, <color-stop>]+
)
<side-or-corner> = [left | right] || [top | bottom]
Edit:
Giving: left top
Matched: left top
Giving: left
Matched: left
Giving: right bottom
Matched: right bottom
Giving: right 20px
Matched: right
Hope this explains it better.
Thank you
If I understood correctly, you want either a side (left/right/top/bottom) or a corner (top-left,bottom-right…).
This can be solved as something like :
you can, of course, reverse the order of the sides for corner notation (to output corners as left-top and not top-left) :
Note that delimiter is your desired delimiter (can be an empty space or a minus sign).
Hope this helps!
P.S. : I heard your call for help on twitter :P.
update
based on your edit, I think now I understand what you need :
This regex now matches a side (left/top/right/bottom) or two sides defined by left & top values, which can be either the direction keywords (left/top/right/bottom) or an actual value (such as
100pxor1.4em).The value regex (
-?\d*(\.\d+)?(px|em|\%)) matches any floating number (even without the first zero :.123instead of0.123) followed by a unit of measurement (here you can supply a full list of units)Here’s some of my (javascript) test which passed:
final update
/(((left|right|(-?\d*(\.\d+)?(px|em|\%)))\s+(top|bottom|(-?\d*(\.\d+)?(px|em|\%))))|(left|right|top|bottom))/