2016-01-13 94 views
-4

我試圖捕獲URL中的%20,並用+'es替換它們,以及去掉其他一些東西,所有優選使用單個正則表達式。正則表達式:使用一個正則表達式替換同一行內的多個模式

具體來說,我想這樣的事情

a%20sentence%20divided%20by%20spaces_123456.html

要變成像這樣

a+sentence+divived+by+spaces

編輯:爲清楚起見,這是至關重要的兩個%20「 s和尾部_1233456.html是針對性的,最好使用一個單一的表達式。

源可以

^([\w]+%20)+.*\.html$(多次出現[\w]+%20,其次爲任意字符,然後.html

有針對性,但我感到困惑如何具體取代雙方的多次出現%20和尾隨'123456'。我猜這將是在朝着正確的方向

^(([\w]+)%20)+([\w]+)_[0-9]+\.html$

$1是的([\w]+)%20$2是第一場比賽中的[\w]+每次出現每次出現,並$3[\w]+了一槍,但我不讓我在尋找(使用文本崇高此)結果:

string: a%20sentence%20divided%20by%20spaces_123456.html 
search: ^(([\w]+)%20)+([\w]+)_[0-9]+\.html$ 
replace: $2+$3 
expected result: a+sentence+divided+by+spaces 
actual result: by+spaces 

那裏我的思路都被打亂任何想法?

+0

[標籤:使用Javascript(將通過正則表達式在年底反正擦除)? – Tushar

+1

用'+'簡單替換'%20'有什麼問題? – ndn

+0

['decodeURIComponent()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent)。 'str = decodeURIComponent(str).replace(/ \ s +/g,'+');' – Tushar

回答

0

您可以使用兩個正則表達式(有可能是雖然更好的解決方案):

var string ="a%20sentence%20divided%20by%20spaces_123456.html"; 
// replace %20 with + 
var regex1 = '%20'; 
var re1 = new RegExp(regex1, 'g'); 
string = string.replace(re1, '+'); 
// trailing _12345 
var regex2 = '([^_]+)_([^.]+)(\.html)$'; 
// match everything except an underscore and capture it in group 1 
// underscore 
// match everything except a dot 
// match the file extension (html in this case) and capture it in group 3 
var re2 = new RegExp(regex2); 
string = string.replace(re2,'$1$3'); 
// replace the string with capture group 1 and 3 
alert(string); 

a JS fiddle這裏。

+0

感謝您的回覆,但是這並不會剝離尾隨的'_123456.html' - 這非常重要。 – Ack

0

取決於捕獲的內容用不同的字符串替換字符串的部分是不容易用正則表達式來完成的。 使用2個正則表達式可以非常容易地完成。但是,如果你真的想只用1正則表達式來做到這一點,這裏是一個解決方案

1個正則表達式解決方案:

original_string = 'a%20sentence%20divided%20by%20spaces_123456.html' 
searched_string = original_string + "+" 
regex : '%20(?=[^\+]*(\+))|_[^_]*$' 
replace : '$1' 
result : a+sentence+divided+by+spaces 

對於解釋:
正則表達式將搜索無論是「 %20「後面的字符與結尾的字符串」 +「並捕獲」「最後的後OR每個字符」 + _「和捕捉任何
然後它會取代被捕獲的字符串,它是匹配的字符串爲」 +「如果」 %20「已經匹配,什麼如果它的結尾字符串
要工作,此正則表達式需要該字符串包含「+」。
這就是爲什麼你需要在你的字符串月底來連接它