2011-04-02 48 views

回答

3

喜歡這個?

var x="omg {wtf} bbq"; 

alert(x.match(/{([^}]+)}/)); 
+0

返回'{}跆拳道,wtf'而不是'wtf' – alex 2011-04-02 03:23:24

+0

獲得第一組,將只包含的文本大括號。請記住,正則表達式中的括號定義了組。 – 2011-04-02 03:25:26

+0

如何刪除組一起,只是它返回'wtf' – alex 2011-04-02 03:26:43

1
"{I want what's between the curly braces}".replace(/{(.*)}/, "$1"); 

這應該工作,歡呼聲。

注:括號你「搞定一切」,即使它是一個空字符串。

更新時間: 如果你要第一個字符,其在一個字符串中間,使用 「匹配」 匹配:

"how are you {I want what's between the curly braces} words".match(/{(.*)}/)[1]; 

你可以這樣做:

console.log("how are you {I want what's between the curly braces} words".match(/{(.*)}/)); 

然後你會看到比賽的項目清單,他們利用任何你想要的。

血淋淋的細節:http://www.w3schools.com/jsref/jsref_obj_regexp.asp

+0

在IE – alex 2011-04-02 03:45:27

+0

中不起作用@alex您使用的是什麼版本的IE?我剛剛在IE9中進行了測試,如下所示:http://img801.imageshack.us/i/reie.png/,其實我也是IE7,8,一切正常。 – Linmic 2011-04-02 03:54:28

19

下面是使用的例子:

var found = [],   // an array to collect the strings that are found 
    rxp = /{([^}]+)}/g, 
    str = "a {string} with {curly} braces", 
    curMatch; 

while(curMatch = rxp.exec(str)) { 
    found.push(curMatch[1]); 
} 

console.log(found); // ["string", "curly"] 
+0

不錯的正則表達式。謝謝。 :) – Tharanga 2017-06-23 11:04:07

1

通過嘗試這種

/[^{\}]+(?=})/g 

例如

歡迎RegExr V2.1 { gskinner.com},{ssd.sd}主機由Media Temple編輯!

它會返回gskinner.com', 'ssd.sd'