問題描述
正則表達式查找和替換 url 不起作用或如何使其起作用 (Regex to Find and Replace url does not work or how to make it work)
Using Regex Hero here are the inputs:
Regular Expression: /category/*
Replacement String: /experiment/$0
Target String: http://google.co.in/blah_blah_blah/domainname.com/category/wp/
Final String:http://google.co.in/blah_blah_blah/domainname.com/experiment//category/wp/
Expected Url
http://google.co.in/blah_blah_blah/domainname.com/experiment/wp/
How do i get the expected URL , is there something wrong in my regex?
‑‑‑‑‑
參考解法
方法 1:
try regex:
/category/(.*)
In regex .
is the wildcard and *
is a "0 or more" qualifier. Therefore, Matching 0 or more (*
) characters (.
) after the forward slash should be expressed as .*
replacement:
/experiment/$1
$0 is a "pseudo group" that holds the entire match, i.e. "/category/...". You need to use parentheses to define other groups so that you can reference these groups in the replacement pattern, hence the (.*)
part in the regex.
方法 2:
You need to change the regex:
/category/([^/]+)
That will match everything up to the next slash. Notice I have also wrapped it in parentheses to capture
it. Alternatively, if you just want EVERYTHING after /category/
use:
/category/(.*)
You then need to change your replacement to:
/experiment/$1
$1
is the first match.
this results in:
http://google.co.in/blah_blah_blah/domainname.com/experiment/wp/
(by Deeptechtons、Pencho Ilchev、LeonardChallis)