简体   繁体   中英

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.

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.

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)) 

I'd agree with trincot and use deconstructoring. According to the Mozilla docs, having the full match go into the 1st index is by design: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec :

Object: result

Property/Index: [0]

Description: The full string of characters matched

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM