I have a list of strings
time:1001 name:foo avg:5.7
time:1002
time:1003 avg:1.2
time:1004 name:f
time:1005 name:bar avg:2.1
I want to pick out the strings which match time:value name:value avg:value
exactly and extract
[time, 1001], [name, foo], [avg, 5.7]
[time, 1005], [name, bar], [avg, 2.1]
using regex: /(w+):s*(?:"([^"]*)"|(S+))/g
code:
const regex = /(w+):s*(?:"([^"]*)"|(S+))/g;
let match = regex.exec(line);
I get all the lines,
[time, 1001], [name, foo], [avg, 5.7]
[time:1002], [name:undefined], [avg, undefined]
[time:1003], [name:undefined], [avg:1.2]
[time:1004], [name:f], [avg, undefined]
[time, 1005], [name, bar], [avg, 2.1]
how do I select the ones with all key values present
3
Answers
You can create your regexp dynamically to use capture groups:
Or use
{3}
to tell that you want exactly 3 key:value pairs in aline and parse a line manually:
Make your regexp match the keys exactly, instead of using
w+
to match anything.One possible approach, which consumes the data-blob entirely as is …
… could be based on a globally flagged regex like …
… which utilizes named capturing groups and gets applied via
matchAll
.Since the resulting iterator’s array-representation features just the valid matches, one can
map
said array, where with each iteration step one does render a valid part of the final result via e.g. a template literal. The mapped array then just needs to bejoin
ed with anewline
/'n'
.The next provided executable example code generates exactly the result the OP was asking for, thus proving all of the above said/explained …