0

I am not much experienced using regex and fighting to solve the problem: I have a url like below:

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

I want to redirect the above url to below url :

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

Moreover I want to do the redirect using aws ALB redirection rule. And I will have to do the same URL redirection with different country-locale pattern. for example en-BZ, en-CA.

I need help how to capture the language-Country part and reform the source URL?

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44

2 Answers2

0

This is the regexp for matching language and country:

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

here is the example

[a-z] for lowercase letter, [a-z]{2} for two lowercase letters, (?<lang>[a-z]{2}) make it a group and name it 'lang', and then a dash '-', and two uppercase letters group and name it 'country', and is contained in two '/'

Since I don't know what's your developing language, say it's PHP, then:

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?://) matches "http://" or "https://"

Simon
  • 647
  • 4
  • 9
0

Using JavaScript following Regular expressions can be helpful:

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

Below are the working examples:

'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"
Vikram
  • 622
  • 1
  • 6
  • 18