Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to have such a regex?

I have a string like this:
124:111,120:444,103:504,494:120,404:111,200:100,

I will use replace() and let’s say I want to select
124:111,120:444,103:504,494:120,404:111,**200:100,**
without actually defining 200:100, but instead having it to work like this:

Define only :100, regex selects everything to the left until "," approaches and everything to the right including first "," => 200:100,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible to have such a regex? Thanks for any information

>Solution :

Regex

,?(\d*?):100

Will match :100 and capture the digits before that:

const regex = /,?(\d*?):100/gm;
const sourceValue = '124:111,120:444,103:504,494:120,404:111,200:100,';
const match = regex.exec(sourceValue);

console.log(match[1]);
// 200

split()

Another option is to split on ,, then check if the right side has the value you’re searching for

const sourceValue = '124:111,120:444,103:504,494:120,404:111,200:100,';
const searchValue = 100;

sourceValue.split(',').forEach(p => {
    const [ l, r ] = p.split(':');
    if (+r === searchValue) {
        console.log(`Found searchValue\n\nLeft\t\t${l}\nRight\t\t${r}\nOriginal\t${p}`);
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading