skip to Main Content

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

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?

3

Answers


  1. Give it a try

        const regex = /(d+.d+)s*-s*(d+.d+)]s*(.*)/;
        const str = "7 [173.88 - 201.839] some text";
        const match = str.match(regex);
        
        if (match) {
          console.log("First number:", match[1]); //173.88
          console.log("Second number:", match[2]); // 201.839
          console.log("Text:", match[3]); // some text
        } else {
          console.log("No match found.");
        }
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. const regex = /(d+.d+)s*-s*(d+.d+)]s*(.*)/;
    const str = "7 [173.88 - 201.839] some text";
    const match = str.match(regex);
    
    console.log("First number:", match[1]);
    console.log("Second number:", match[2]);
    console.log("Text:", match[3]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search