如何在URL(字符串)中添加/替换语言


How can I add/replace language in the URL (string)?

以下是我迄今为止所尝试的:

/(?:'/(en('?|$)|fa('?|$)))|'?/

输入:

http://localhost:8000/search/fa?q=sth
http://localhost:8000/search?q=sth
http://localhost:8000/search
http://localhost:8000/search/fa

预期输出:

http://localhost:8000/search/en?q=sth
http://localhost:8000/search/en?q=sth
http://localhost:8000/search/en
http://localhost:8000/search/en

正如你所看到的,我需要匹配?,但不选择它。我还需要在第三个URL的末尾添加/en

如何修复我的模式?

^.*?'/('w{2,})(?:'?(.*?)|)$

这可能工作

下面是使用此regex的一个简单实现。

演示