skip to Main Content

It’s possible that I will either have

boundary=-------Embt-Boundary--1261032946D275CF

or

boundary="-------Embt-Boundary--1261032946D275CF"

and I want to just extract -------Embt-Boundary--1261032946D275CF from the String.

How should I formed the regex? I have tried boundary="?(.+)("?) but it only works for the first but for the second I’ll get the last double quote in my extracted string (eg. -------Embt-Boundary--1261032946D275CF").

2

Answers


  1. You need:

    boundary="?([^"]+)"?
    

    Only one capture group used.

    JS Demo:

    const input1 = 'boundary="-------Embt-Boundary--1261032946D275CF"';
    const input2 = 'boundary=-------Embt-Boundary--1261032946D275CF';
    const regex = /boundary="?([^"]+)"?/;
    
    const match1 = regex.exec(input1);
    const match2 = regex.exec(input2);
    
    console.log(match1[1]);
    console.log(match2[1]);

    The regular expression matches as follows:

    Node Explanation
    boundary= ‘boundary=’
    "? ‘"’ (optional (matching the most amount possible))
    ( group and capture to 1:
    [^"]+ any character except: " (1 or more times (matching the most amount possible))
    ) end of 1
    "? ‘"’ (optional (matching the most amount possible))
    Login or Signup to reply.
  2. I believe flutter is Dart, which uses JavaScript regex specification, yes? Use capture groups in this way:

    boundary=("?)(.*)(1)
    

    Group 1 will capture a quote if there is one. Group 2 will capture your desired result. Then, 1 will match the quote, if there was one, or nothing, if the quote was not present.

    regex101

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search