简体   繁体   中英

Replace everything except a matching pattern in regex

I'm attempting to delete everything but a matching pattern using javascripts .replace() function and regex.

I want to save the digits from the "date" field, ie 11 10 2021 or 9 10 2021. This regex /[\d]{1,2} [0-9]{2} [0-9]{4}/g matches to the date patterns, however when using .replace(regex, '') it replaces those digits rather than saving them. I'm just wondering how to "invert" the pattern to save the digits and replace everything else.

Example strings:

SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"date":"11 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]
    
[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]

Use regex exec or string matchAll instead string replace

exec

 const regex = /[\d]{1,2} [\d]{2} [\d]{4}/g; const str = `SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a", "userId":"email@gmail.com", "date":"11 10 2021", "timeStamp":"2:26:", "formResponse":"Survey completed"}] [{"_id":"616392e41a03eed562de2e8a", "userId":"email@gmail.com", "date":"9 10 2021", "timeStamp":"2:26:", "formResponse":"Survey completed"}]`; let match; while(match = regex.exec(str)) { console.log(match[0]); }

matchAll

 const iterator = `SURVEY API RESULT LANDING: [{"_id":"616392e41a03eed562de2e8a", "userId":"email@gmail.com", "date":"12 10 2021", "timeStamp":"2:26:", "formResponse":"Survey completed"}] [{"_id":"616392e41a03eed562de2e8a", "userId":"email@gmail.com", "date":"9 10 2021", "timeStamp":"2:26:", "formResponse":"Survey completed"}]`.matchAll(/[\d]{1,2} [\d]{2} [\d]{4}/g); console.log(Array.from(iterator).map(m => m[0]));

To find a single date, try the following

`[{"_id":"616392e41a03eed562de2e8a",
"userId":"email@gmail.com",
"date":"9 10 2021",
"timeStamp":"2:26:",
"formResponse":"Survey completed"}]`.replace(/.*([\d]{1,2} [0-9]{2} [0-9]{4}).*/gms, "$1");

RegExp reference https://javascript.info/regexp-introduction

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