2012-10-12 49 views
0

問了很多次,但我不能得到它的工作...如何正則表達式中的兩個令牌之間的字符串?

我有這樣的字符串:

"text!../tmp/widgets/tmp_widget_header.html" 

,我試圖這樣來提取widget_header

var temps[i] = "text!../tmp/widgets/tmp_widget_header.html"; 
var thisString = temps[i].regexp(/.*tmp_$.*\.*/)) 

但那不起作用。

有人能告訴我我在做什麼錯嗎?

謝謝!

+2

什麼是你期待'$'在你的正則表達式嗎? –

+0

這是我想開始提取字符串的地方。差不多就是 – frequent

回答

1
var s = "text!../tmp/widgets/tmp_widget_header.html", 
    re = /\/tmp_([^.]+)\./; 

var match = re.exec(s); 

if (match) 
    alert(match[1]); 

這將匹配:

  • 一個/字符
  • 字符tmp_
  • 一個或多個不屬於.字符任意字符。這些被捕獲。
  • 一個.字符

如果沒有發現匹配時,將在所得到的陣列的指數1

+0

。如果我有'text!../ tmp/page/tmp_page_footer.html',那麼我會回到'[「/ tmp_page_footer。」 ,「page_footer」]。任何想法爲什麼? – frequent

+0

@frequent:這不就是你想要的結果嗎?目標文本「page_footer」位於結果數組的索引「[1]」處。 –

+0

哦,我沒有注意到。 – frequent

3

這將打印widget_header

var s = "text!../tmp/widgets/tmp_widget_header.html"; 
var matches = s.match(/tmp_(.*?)\.html/); 
console.log(matches[1]); 
+0

也謝謝。我與其他答案一起去,因爲它更快。 – frequent

1

在您的代碼:

var temps[i] = "text!../tmp/widgets/tmp_widget_header.html"; 
var thisString = temps[i].regexp(/.*tmp_$.*\.*/)) 

你是在說:

「匹配任意數量的任何字符開頭的字符串,然後」 tmp_「,然後是輸入結束,然後是任意數量的句點。」

.* : Any number of any character (except newline) 
tmp_ : Literally "tmp_" 
$ : End of input/newline - this will never be true in this position 
\. : " . ", a period 
\.* : Any number of periods 

加上使用正則表達式()函數,你需要傳遞一個字符串,利用斜線不是正則表達式符號使用字符串符號像var re = new RegExp("ab+c")var re = new RegExp('ab+c')時。您還有一個額外的或缺少的圓括號,並且實際上沒有捕獲字符。

你想要做的是:

「查找,通過輸入的開頭引導的字符串,後面跟着一個或多個任意字符,其次是‘tmp_’;其次是一個週期,其次是一個或多個任意字符,後跟輸入結尾; t包含一個或多個任意字符。捕獲該字符串。「

所以:

var string = "text!../tmp/widgets/tmp_widget_header.html"; 
var re = /^.+tmp_(.+)\..+$/; //I use the simpler slash notation 

var out = re.exec(string); //execute the regex 

console.log(out[1]);   //Note that out is an array, the first (here only) catpture sting is at index 1 

此正則表達式/^.+tmp_(.+)\..+$/意味着:

^ : Match beginning of input/line 
.+ : One or more of any character (except newline), "+" is one or more 
tmp_ : Constant "tmp_" 
\. : A single period 
.+ : As above 
$ : End of input/line 

你也可以使用它作爲RegEx('^.+tmp_(.+)\..+$');不,當我們使用RegEx();我們沒有斜槓標誌,相反,我們使用引號(單或雙將工作),將其作爲字符串傳遞。

現在這也匹配var string = "Q%$#^%$^%$^%$^43etmp_ebeb.45t4t#$^g"out == 'ebeb'。因此,根據具體用途,您可能希望用括號內的「[]」字符列表來替代任何用於表示任意字符(換行符除外)的「。」,因爲這可能會過濾掉不需要的結果。你的小豬可能會有所不同。

欲瞭解更多信息,請訪問:https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

相關問題