qt - 用于测试文件名是否以后缀结尾的正则表达式:错误结果
问题描述
我正在使用此功能
exportAsIndustryFormats('phz', 'file:///home/m3/Documents/exported/layers6.phz');
function exportAsIndustryFormats(suffixStr, file) {
var endsWithSuffix = new RegExp('/\.' + suffixStr + '$/')
var doesEnd = endsWithSuffix.test(file) // This test result is wrong!?
console.log("Does file ends with suffix ===", doesEnd)
if(doesEnd) {
} else {
file += '.' + suffixStr
}
console.log("Suffix ===", suffixStr)
console.log("file ===", file)
// ...
}
我的应用程序记录了这不是预期的:
// Input file URL:
qml: fileUrl === file:///home/m3/Documents/exported/layers6.phz
qml: Does file ends with suffix === false
qml: Suffix === phz
// Adds an extra suffix, since it thinks the suffix is NOT there:
qml: file === file:///home/m3/Documents/exported/layers6.phz.phz
我无法弄清楚代码有什么问题。有人可以帮忙吗?
解决方案
首先,您应该在您的情况下使用 this 定义新的正则表达式new RegExp('.' + suffixStr + '$')
。new Regex
将为您生成其余部分。
其次,您可以通过将原始字符串按目标字符串的长度切片来检查输入字符串的最后一部分,如下所示:
var doesEnd = endsWithSuffix.test(file.slice(-(suffixStr.length + 1)));
最终代码:
exportAsIndustryFormats('phz', 'file:///home/m3/Documents/exported/layers6.phz');
function exportAsIndustryFormats(suffixStr, file) {
var endsWithSuffix = new RegExp('.' + suffixStr + '$')
var doesEnd = endsWithSuffix.test(file.slice(-(suffixStr.length + 1))); // This test result is wrong!?
console.log("Does file ends with suffix ===", doesEnd)
if(doesEnd) {
} else {
file += '.' + suffixStr
}
console.log("Suffix ===", suffixStr)
console.log("file ===", file)
// ...
}
推荐阅读
- java - firebase UI更新后无法使viewholder最终
- openxml - Aspose.Cells - 打开由 EPPlus 生成的 OpenXml 文件
- php - print_r($_POST) 不打印任何内容
- java - 如何使用名称将 id 值从一个表传递到另一个表并将信息存储到数据库
- wordpress - WordPress 网站中的 Http 错误 500
- javascript - 通过查询字符串截断加号传递变量
- git - 推送标签时如何触发VSTS构建和发布?
- python - 使用python获取随机单词
- terraform - 是否可以向 terraform 模块添加模板或循环
- python - Python附加具有numpy数组类型的类属性