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

Regex, match with different patterns at once

I have a giant string with this format:

5 [105.68 - 143.759] some text
6 [143.759 - 173.88] some text
7 [173.88 - 201.839] some text
...

I want to match:

  1. Numbers including the dot between [ and -, this is the regex: /(?<=\[).*?(?=\ )/
  2. Numbers including the dot between - and ], this is the regex: /(?<=\-\ ).*?(?=\])/
  3. All text after ] , for this I use this regex: /(?<=\]\ ).*/

So for example for the first line the matches will be: 105.68, 143.759 and some text

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

This works but I want to know if is possible to match those three patterns at once, I tried concatenating the different patterns with | but it didn’t work with this:

const re = /(?<=\[).*?(?=\ )|(?<=\-\ ).*?(?=\])|(?<=\-\ ).*?(?=\])/
const regex = RegExp(re, 'gm')
regex.exec("7 [173.88 - 201.839] some text")

Output 1st time calling exec: Array [ "201.839" ]
Output 2nd time calling exec: Array [ "173.88" ]
Output 3rd time calling exec: null

Is there a way to get all this (and the actual text, not null) in a single call?

>Solution :

You could use match() with three capture groups:

var input = "5 [105.68 - 143.759] some text";
var matches = input.match(/\[(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\]\s+(.*)/);
console.log("1st num: " + matches[1]);
console.log("2nd num: " + matches[2]);
console.log("text:    " + matches[3]);

If you need to apply this to a multiline string, then you could split the string by space and then apply the above to each line.

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