簡體   English   中英

麻煩在正則表達式中使用string.replace

[英]trouble using string.replace with regex

給定這樣的正則表達式:

http://rubular.com/r/ai1LFT5jvK

我想使用string.replace用我選擇的字符串替換“ subdir”。

myStr.replace(/^.*\\/\\/.*\\.net\\/.*\\/(.*)\\/.*\\z/,otherStr)

僅返回相同的字符串,如下所示: http : //jsfiddle.net/nLmbV/

如果您查看Rublar,它似乎可以捕捉到我想要捕捉的東西,但是在Fiddle上,它並不能替代它。

我想知道為什么會這樣,以及我在做什么錯。 正確的正則表達式或replace調用的正確實現會很好,但是最重要的是,我想了解自己做錯了什么,以便將來可以避免。

編輯

我更新了小提琴,將正則表達式從以下位置更改:

/^.*\/\/.*\.net\/.*\/(.*)\/.*\z/

 /^.*\/\/.*\.net\/.*\/(.*)\/.*$/

根據小提琴,它只是返回hello而不是https://xxxxxxxxxxx.cloudfront.net/dir/hello/Slide1_v2.PNG

正則表達式中只有那個\\z

您可能忘了用$符號代替它。 JavaScript使用^$作為錨點,而Ruby使用\\A\\z


回答您的編輯:

比賽總是被整體替換。 您需要將要替換零件的左側和右側都分組,然后將其重新插入替換中:

url.replace(/^(.*\/\/.*\.net\/.*\/).*(\/.*)$/,"$1hello$2")

在我被打倒之前,我知道問題要問正則表達式。 如果不編寫極其復​​雜的正則表達式,使用正則表達式幾乎不可能可靠地處理此答案URL的原因。 可以做到,但是會傷到你的頭! 如果在瀏覽器中執行此操作,則可以在腳本中使用A標記,以簡化操作。 A標簽知道如何將它們解析為小塊,它使您可以獨立地修改小塊,因此您只需要處理路徑名:

//make a temporary a tag
var a = document.createElement('a');
//set the href property to the url you want to process
a.href = "scheme://host.domain/path/to/the/file?querystring"
//grab the path part of the url, and chop up into an array of directories
var dirs = a.pathname.split('/');
//set 2nd dir name - array is ['','path','to','file']
dirs[2]='hello';
//put the path back together
a.pathname = dirs.join('/');

a.href現在包含所需的URL。 當您回來以后更改代碼時,會保留更多的行,但還會留下更多的頭發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM