const regex = /(X(-?\d+(?:\.\d+)?))?\s*(Y(-?\d+(?:\.\d+)?))?/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(X(-?\\d+(?:\\.\\d+)?))?\\s*(Y(-?\\d+(?:\\.\\d+)?))?', 'gm')
const str = `N14 X411 Y279.05
N15 G2 X33 Y280.4 I.001 J4.00
N16 G1 X408 Y280.4
N17 G2 X402.3 Y280.09 I-3 J2.65
N18 G1 X402.3 Y280.09
N19 G2 X402.09 Y285.79 I2.7 J2.95
N20 G1 X402.09 Y285.79
N3 G40 Y6000
N3 G40 X-6000`;
// 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