优雅的Regex在控制结构中的应用

Elegant Regex Use in Control Structure

本文关键字:应用 控制结构 Regex      更新时间:2023-09-26

我正在寻找一种在控制结构中使用正则表达式的更优雅的方法。我希望能够使用匹配执行操作,而无需在需要的地方之外声明regex,也无需执行两次匹配操作。

以下是我为简洁起见编辑的代码:

/* I'm not a fan of declaring this outside of where it will be used */
var regexYoutube = new RegExp(/((youtube'.com'/watch'?v=)|(youtu'.be'/))(.{11})/i);
if(isImage(content)){
    data.type = 'IMAGE';
    data.content = toImage(content);
    postContent(data);
} else if (isVideo(content)){
    data.type = 'VIDEO';
    data.content = getVideoThumb(content);
    postContent(data);
} else {
    data.type = 'STRING';
    data.content = content;
    postContent(data);
}
function isImage(content){
    if(content.indexOf(".jpg") > -1)
        return true;
    else
        return false;
}
function isVideo(content){
    return regexYoutube.test(content);
}
function getVideoThumb(content){
    /* I don't want to perform a test followed by an exec */
    var youtubeMatch = regexYoutube.exec(content);
    return "http://img.youtube.com/vi/"+youtubeMatch[4]+"/0.jpg";
}

我不在,这是非常挑剔的,但如果这是一种必要的邪恶,我会接受的。

我会将isVideo函数修改为其他函数,例如execYouTubeRegex,并返回.exec的值。然后,不要在execYouTubeRegex外部声明regex,而是在函数内部声明它。

然后,您可以将isYoutube替换为对execYouTubeRegex的调用并检查它是否返回了任何内容,并将在其他地方使用的exec调用替换为使用相同的函数。

这本身就是一种邪恶,因为它将函数的副作用用于其他事情(简单的返回值是check(。但是,它是在不使用正则表达式的地方定义正则表达式的替代方案。

正如一篇评论中提到的,这并不是真正的邪恶。保持你的范围小,它不会变得太混乱-代码对我来说很可读。