const regex = /^[ \t]*([0]|([-+]?(\d*\.)?\d+)(cm|mm|in|px|pt|pc|Q|em|ex|ch|rem|vw|vh|vmin|vmax|%)){1}([\t ]+([0]|([-+]?(\d*\.)?\d+)(cm|mm|in|px|pt|pc|Q|em|ex|ch|rem|vw|vh|vmin|vmax|%))){0,3}[\t ]*$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^[ \\t]*([0]|([-+]?(\\d*\\.)?\\d+)(cm|mm|in|px|pt|pc|Q|em|ex|ch|rem|vw|vh|vmin|vmax|%)){1}([\\t ]+([0]|([-+]?(\\d*\\.)?\\d+)(cm|mm|in|px|pt|pc|Q|em|ex|ch|rem|vw|vh|vmin|vmax|%))){0,3}[\\t ]*$', 'gm')
const str = `0
0
0px
0px 0px 0px 0
0 0
0cm 0px 0ch 0%
0 0
0 0 0
0 0 0
0 0 0 0
2px 0
+2px
-3px
0 2px
3cm
0px
0px 0px 0px
1px
2px 2px
3px 3px 3px
4px 4px 4px 4px
+4px -4px -4px +4px
-1px
-2px -2px
-3px -3px -3px
-4px -4px -4px -4px
1%
2% 2vh
3vw 3vh 3%
4cm 4pt -4vmin 4vmax
# Errors - must not match
00
0 0px 00
1px-2px
2px2px
3pxf 3px 3px sdsd
4px-4px 4px 4px
4px4px4px4px
4px 4px 4px 4-px
-4px-4px-4px-4px
--3px
+-3px
-4px-4px -4px- 4px
-4
+5
+0px -0
+0`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions