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:
- Numbers including the dot between
[and-, this is the regex:/(?<=\[).*?(?=\ )/ - Numbers including the dot between
-and], this is the regex:/(?<=\-\ ).*?(?=\])/ - 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
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.