如何使用斜杠约束提取字符串的一部分?

How to extract part of a string with slash constraints?

你好,我有一些这样命名的字符串:

BURGERDAY / PPA / This is a burger fest

我试过使用正则表达式来获取它,但我似乎无法正确获取它。

输出应该只是 This is a burger fest 的最终字符串(没有第一个空格)

在这里,我们可以在到达最后一个斜杠后跟任意数量的空格后捕获我们想要的输出:

.+\/\s+(.+)

其中 (.+) 收集我们希望收集的内容 return。

const regex = /.+\/\s+(.+)/gm;
const str = `BURGERDAY / PPA / This is a burger fest`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

DEMO

建议

根据revo的建议,我们也可以使用这个表达式,这样更好:

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

根据 Bohemian 的建议,根据我们希望使用的语言,可能不需要转义正斜杠,这适用于 JavaScript:

.+/\s+(.+)

此外,我们假设在目标内容中,我们不会有正斜杠,否则我们可以根据其他可能的情况更改我们的约束条件 inputs/scenarios。

注意:这是一个蟒蛇般的回答(我的错误)。我将保留它的价值,因为它可以应用多种语言

另一种方法是拆分它然后重新加入它。

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

这里分四步:

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

简而言之:

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

注意:我觉得 str.join(..., ...) 在某些情况下比 '...'.join(...) 更具可读性。虽然这是相同的调用。