-2

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)

Emma
  • 27,428
  • 11
  • 44
  • 69

2 Answers2

3

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.

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    What you are doing could be achieved in another way: `\/ +([^\/]*)$` – revo May 29 '19 at 00:32
  • 1
    This assumes there will be no forward slashes in the target content (not confirmed by OP). Also, a small note: You don’t need to escape forward slashes, ie this is the same regex: `.+/\s+(.+)`. If your language (eg JS, but not java for example) requires you to escape it because the forward slash is part of your language, then sure, show it in situ. – Bohemian May 29 '19 at 01:36
0

Note: This is a pythonish answer (my mistake). I'll leave this for it's value as it could apply many languages

Another approach is to split it and then rejoin it.

data = 'BURGERDAY / PPA / This is a burger fest'

Here it is in four steps:

parts = data.split('/')   # break into a list by '/'
parts = parts[2:]         # get a new list excluding the first 2 elements
output = '/'.join(parts)  # join them back together with a '/'
output = output.strip()   # strip spaces from each side of the output

And in one concise line:

output= str.join('/', data.split('/')[2:]).strip()

Note: I feel that str.join(..., ...) is more readable than '...'.join(...) in some contexts. It is the identical call though.

gahooa
  • 131,293
  • 12
  • 98
  • 101