【问题标题】:Regex : Reforming a url path if a particular string pattern is found in the path正则表达式:如果在路径中找到特定的字符串模式,则重新调整 url 路径
【发布时间】:2019-12-05 09:41:10
【问题描述】:

我没有太多使用正则表达式和努力解决问题的经验: 我有一个如下网址:

http://example.com/ja-JP/blog/12345

我想将上面的网址重定向到下面的网址:

http://jp.example.com/ja/blog/12345

此外,我想使用 aws ALB 重定向规则进行重定向。 而且我将不得不使用不同的国家语言环境模式进行相同的 URL 重定向。 例如 en-BZ、en-CA。

我需要帮助如何捕获语言国家部分和修改源 URL?

【问题讨论】:

    标签: regex redirect aws-elb


    【解决方案1】:

    这是匹配语言和国家的正则表达式:

    \/(?<lang>[a-z]{2})-(?<country>[A-Z]{2})\/  
    

    here is the example

    [a-z] 表示小写字母,[a-z]{2} 表示两个小写字母,(?[a-z]{2}) 将其组成一个组并将其命名为 'lang',然后是破折号 '- ',和两个大写字母组合并命名为'country',并包含在两个'/'中

    既然不知道你的开发语言是什么,就说是PHP,那么:

    preg_match('/\/(?<lang>[a-z]{2})-(?<country>[A-Z]{2})\//' ,$url, $matches);
    // $matches['lang']='ja' $matches['country']='JP'
    
    $url = preg_replace('/\/(?<lang>[a-z]{2})-(?<country>[A-Z]{2})\//', '/'.$matches['lang'].'/', $url);
    // $url = 'https://example.com/ja/blog/12345'
    
    $url = preg_replace('/(https?:\/\/)/', '$1'.$matches['country'].'.', $url);
    // $url = 'https://JP.example.com/ja/blog/12345'
    

    (https?://) 匹配“http://”或“https://”

    【讨论】:

      【解决方案2】:

      Regular expressions 之后使用 JavaScript 会有所帮助:

      /(example.com\/[a-z]{2,})-([a-z]{2,})/i
      

      以下是工作示例:

      'http://example.com/ja-JP/blog/12345'.replace(/(example.com\/[a-z]{2,})-([a-z]{2,})/i, '$2.$1');
      // Outputs "http://JP.example.com/ja/blog/12345"
      
      'http://example.com/en-BZ/blog/12345'.replace(/(example.com\/[a-z]{2,})-([a-z]{2,})/i, '$2.$1');
      // Outputs "http://BZ.example.com/en/blog/12345"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-11
        • 2018-12-28
        • 2019-08-19
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        相关资源
        最近更新 更多