Search code examples
regexregex-lookaroundsregex-groupregex-greedy

How to extract part of a string with slash constraints?


Hello I have some strings named like this:

BURGERDAY / PPA / This is a burger fest

I've tried using regex to get it but I can't seem to get it right.

The output should just get the final string of This is a burger fest (without the first whitespace)


Solution

  • Here, we can capture our desired output after we reach to the last slash followed by any number of spaces:

    .+\/\s+(.+)
    

    where (.+) collects what we wish to return.

    const regex = /.+\/\s+(.+)/gm;
    const str = `BURGERDAY / PPA / This is a burger fest`;
    const subst = `$1`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log(result);

    DEMO

    Advices

    Based on revo's advice, we can also use this expression, which is much better:

    \/ +([^\/]*)$
    

    According to Bohemian's advice, it may not be required to escape the forward slash, based on the language we wish to use and this would work for JavaScript:

    .+/\s+(.+)
    

    Also, we assume in target content, we would not have forward slash, otherwise we can change our constraints based on other possible inputs/scenarios.