首页 > 解决方案 > 用于测试文件名是否以后缀结尾的正则表达式:错误结果

问题描述

我正在使用此功能

    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

我无法弄清楚代码有什么问题。有人可以帮忙吗?

标签: qtqml

解决方案


首先,您应该在您的情况下使用 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)

        // ...
    }


推荐阅读