regex - 如何提取带有斜线约束的字符串的一部分?
问题描述
你好我有一些这样命名的字符串:
BURGERDAY / PPA / This is a burger fest
我已经尝试使用正则表达式来获取它,但我似乎无法正确使用它。
输出应该只是得到最后的字符串This is a burger fest
(没有第一个空格)
解决方案
在这里,我们可以在到达最后一个斜线后跟任意数量的空格后捕获我们想要的输出:
.+\/\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+(.+)
此外,我们假设在目标内容中,我们不会有正斜杠,否则我们可以根据其他可能的输入/场景来改变我们的约束。
推荐阅读
- excel - 对象列表行的方法(删除或添加)失败(然后崩溃)VBA
- awk - 如何提取文档的一部分并将其保存到新文档(命令行 Mac)
- firebase - onCall firebase 云功能的 CORS 问题(GCP 防火墙规则)
- apollo - 在节点中使用阿波罗 - (无反应)
- python - 过滤布尔字段
- python - Librosa - 如何为立体声音频创建梅尔频谱图?
- scala - 类加载器在使用 foreach 时为 None 加载一个类
- powershell - 如何动态调用具有相同参数的 2 个不同的 cmdlet?(不是动态参数。)
- reactjs - 下拉状态未保留在 React 中
- python - 设置变量等于 sqlite3+Python 数据库条目