简体   繁体   English

难以将正则表达式匹配到过滤方法

[英]Having difficulty matching regex to filter method

Doing a challenge, went a much more complicated route than the solution provided, but now I want to solve the regex filter issue I've stumbled upon. 进行挑战,比提供的解决方案要复杂得多,但是现在我想解决我偶然发现的regex过滤器问题。

Everything works fine until the the second to last line of the currentFileExt() function. 一切正常,直到currentFileExt()函数的倒数第二行。 I originally planned on using map, but after looking through similar StackOverflow solutions I figured .filter() is more appropriate. 我最初计划使用map,但是在浏览了类似的StackOverflow解决方案之后,我发现.filter()更合适。 Sadly, I can't seem to get the filter to check against the regex I provided. 可悲的是,我似乎无法获得用于检查我提供的正则表达式的过滤器。

Perhaps it's a misunderstanding on my part, but I am using the filter to match each string element of the split toArr array, if it matches the regex it should get filtered. 也许这对我来说是一个误解,但是我使用过滤器来匹配split toArr数组中的每个字符串元素,如果它匹配正则表达式,则应该对其进行过滤。 Unfortunately, that doesnt appear to be happening. 不幸的是,这似乎没有发生。

function findFileName(fileName) {
    let detect = (fileName.match(/\.+/g)) ? currentFileExt() : alert("Please enter");
    return detect;

    function currentFileExt() {
        let toArr = fileName.split('');
        let fileExtArr = [];
        // let validCharacter = new RegExp(/\.[a-z]+/, 'g');
        let validCharacter = /\.[a-z]+/;
        fileExtArr = toArr.filter( (element) => { element.match(validCharacter) });
        return fileExtArr.join('');
    }  
}

findFileName('java.java');

One of the issues is that your filter callback function isn't returning any values. 问题之一是您的过滤器回调函数未返回任何值。 In order to do that with an arrow function with a body, you need to add a return keyword or better yet just remove the body. 为了使用带有主体的箭头功能来执行此操作,您需要添加return关键字或更好的方法是删除主体。

String#match is also probably not the method you're looking for since that returns an array of matches or null if there are no matches. String#match也可能不是您要查找的方法,因为它会返回一个匹配数组,如果没有匹配项,则返回null。 If you use RegExp#test , you will get a boolean depending if the string matches the regular expression. 如果使用RegExp#test ,则将获得一个布尔值,具体取决于字符串是否匹配正则表达式。

So maybe the following will suit your needs: 因此,以下内容可能会满足您的需求:

function findFileName(fileName) {
    const detect = (fileName.match(/\.+/g)) ? currentFileExt() : alert("Please enter");
    return detect;

    function currentFileExt() {
        const toArr = fileName.split('');
        const validCharacter = /\.[a-z]+/;
        const fileExtArr = toArr.filter(element => validCharacter.test(element));
        return fileExtArr.join('');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM