在您的代碼:
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
什麼是你期待'$'在你的正則表達式嗎? –
這是我想開始提取字符串的地方。差不多就是 – frequent