【问题标题】:Js regEx parsing woesJs regEx 解析问题
【发布时间】:2014-07-10 16:57:49
【问题描述】:

所以我在解析字符串时遇到了一些麻烦。我需要解析出“images/foo/bar/anotherfoo/imageId” 来自

"url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)"

我曾尝试使用 regEx,但对于如此庞大且特定的子字符串,我对它们的了解不够。任何帮助都会有所帮助,谢谢。

【问题讨论】:

  • 我不确定您是否提供了足够的信息来解决您的问题。有哪些不同的可能路径?该路径的哪些部分将是一致的?
  • "url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)".match(/\/images\/.*/);
  • 嘿 caspian,代码块中的字符串是需要解析的,它上面的图像字符串是我需要的位。因此,我不确定您提到可能的路径或一致性的评论意味着什么。
  • Karl,我运行时那个匹配函数有问题。

标签: javascript jquery regex parsing


【解决方案1】:

对于这个特定的字符串,如果你坚持使用正则表达式,可以使用如下:

var s = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)';
    s = s.replace(/.*(?=images)|\W$/g, '');

console.log(s); //=> 'images/foo/bar/anotherfoo/imageId'

或者使用字符串match()方法..

var s = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)',
    r = s.match(/images[^)]*/);

console.log(r[0]); //=> 'images/foo/bar/anotherfoo/imageId'

【讨论】:

    【解决方案2】:

    所以我看到的是,您有一些基本 url,http://some/folder/path/,围绕着 CSS url()。试试以下:

    var base_url    = 'http://some/folder/path/';
    var search      = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)';
    
    // That replace is adding back slashes to the base_url so that the regex expression 
    // doesn't get confused. You could also just remove it entirely, but since you wanted
    // a regex based expression...
    var pattern     = '/url(' + base_url.replace(/\//g, '\\/') + '([\w\/]+)\))/i';
    
    if(regex.test(input))
    {
        var matches = input.match(regex);
        for(var match in matches)
        {
            alert(matches[match]);
        } 
    }
    else
    {
        alert("No matches found!");
    }
    

    如果您想了解有关正则表达式的更多信息,我建议您转到 RegexOne 获取教程和练习 - 边做边学。

    【讨论】:

    • 这很好,但我正在为 hwnd 提供答案,以便更简洁地解决我的问题。是的,我正在尝试从 css url() 解析出文件路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多