首页 > 解决方案 > 如何提取带有斜线约束的字符串的一部分?

问题描述

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

BURGERDAY / PPA / This is a burger fest

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

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

标签: regexregex-lookaroundsregex-groupregex-greedy

解决方案


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

.+\/\s+(.+)

where(.+)收集我们希望返回的内容。

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);

演示

建议

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

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

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

.+/\s+(.+)

此外,我们假设在目标内容中,我们不会有正斜杠,否则我们可以根据其他可能的输入/场景来改变我们的约束。


推荐阅读