Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the whole match non-capturing in RegEx

I have a regex like the following:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(regex);

console.log(result)

Here, the result is having the first item as a whole match, is it possible to exclude the whole match from the result in anyway? Currently I ended up doing a shift() on the result, just wondering if the whole match can me marked as non-capturing in anyway.

like image 575
sabithpocker Avatar asked Nov 23 '25 12:11

sabithpocker


2 Answers

You can use destructuring to split-off the first value from the result array with [,...result]:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const [,...result] = "1988-02-01 12:12:12".match(regex);

console.log(result)

If you know the input format is OK, then you can do:

result = "1988-02-01 12:12:12".match(/\d+/g)

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(/\d+/g);

console.log(result)

Or with a bit more checking: .match(/(^\d{4}|\b\d{2})\b/g)

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(/(^\d{4}|\b\d{2})\b/g);

console.log(result)

Additionally, if you want to have the array with the numeric data type equivalents, then map using Number as callback function:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const [,...result] = ("1988-02-01 12:12:12".match(regex)||[]).map(Number);

console.log(result)

The additional ||[] treats the case where the pattern does not match, and exchanges the null with an empty array.

like image 128
trincot Avatar answered Nov 25 '25 02:11

trincot


You can take a look at named groups

const regex = /((?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})) (?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/;

const result = "1988-02-01 12:12:12".match(regex).groups;

console.log(result)

console.log(Object.values(result))
like image 21
Taki Avatar answered Nov 25 '25 01:11

Taki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!