2013-07-22 188 views
109

我想寫一個正則表達式返回一個括號之間的字符串。例如:我想駐留在字符串之間的字符串「(」和「)」正則表達式獲取Javascript中的括號之間的字符串

I expect five hundred dollars ($500). 

將返回

$500 

找到Regular Expression to get a string between two strings in Javascript

但我是新與正則表達式。我不知道如何在正則表達式中使用'(',')'

+0

可能重複的[正則表達式找到包括兩個字符之間的字符串,同時排除定界符(http://stackoverflow.com/questions/1454913/regular-expression-to- find-a-string-included-between-two-characters-while-exclu) –

+0

您可以使用go-oleg的解決方案,稍作修改以測試美元符號:'var regExp =/\(\ $([^) ] +)\)/;' –

回答

303

您需要創建一組轉義(與\)括號(與圓括號匹配)和一組創建捕獲的常規圓括號組:

var regExp = /\(([^)]+)\)/; 
var matches = regExp.exec("I expect five hundred dollars ($500)."); 

//matches[1] contains the value between the parentheses 
console.log(matches[1]); 

擊穿:

  • \(:匹配的開口括號
  • (:開始捕獲組
  • [^)]+:匹配一個或多個非)字符
  • ):端捕獲組
  • \):匹配閉的貨幣後括號

這裏是關於RegExplained

+11

+1不錯,像魅力一樣工作。我想添加你添加這個http://tinyurl.com/mog7lr3在你的視覺解釋。 – Praveen

+5

@ user1671639:已更新。感謝您的鏈接! –

+0

如果我需要在[某些事物] – CodeGuru

3

只是稍微數字的視覺解釋標誌:\(.+\s*\d+\s*\)應該工作

\(.+\) fo R內支架什麼

+1

這將適用於示例文本,但如果在字符串後面出現另一個'''',例如'我期望500美元(500美元)「。 (但我要付錢)。「+」的貪婪將會捕捉更多。 –

+0

@Denomales那麼你會如何捕獲這些字符串的兩個實例。理想情況下,我正在做類似的事情,但我想要: '($ 500)'和'(但我要付錢)' 匹配,但在兩個分開的比賽,而不是被視爲一個單一的匹配項目? 在此先感謝! –

23

嘗試字符串操作:

var txt = "I expect five hundred dollars ($500). and new brackets ($600)"; 
var newTxt = txt.split('('); 
for (var i = 1; i < newTxt.length; i++) { 
    console.log(newTxt[i].split(')')[0]); 
} 

或正則表達式(這有點slow compare to the above

var txt = "I expect five hundred dollars ($500). and new brackets ($600)"; 
var regExp = /\(([^)]+)\)/g; 
var matches = txt.match(regExp); 
for (var i = 0; i < matches.length; i++) { 
    var str = matches[i]; 
    console.log(str.substring(1, str.length - 1)); 
} 
+2

今天在Chrome 59.0.3071上運行jsperf,正則表達式的速度提高了8% –

0
var str = "I expect five hundred dollars ($500) ($1)."; 
var rex = /\$\d+(?=\))/; 
alert(rex.exec(str)); 

將匹配的第一個數字開始以$跟着'')。 ')'不會成爲比賽的一部分。該代碼提醒第一場比賽。

var str = "I expect five hundred dollars ($500) ($1)."; 
var rex = /\$\d+(?=\))/g; 
var matches = str.match(rex); 
for (var i = 0; i < matches.length; i++) 
{ 
    alert(matches[i]); 
} 

此代碼提示所有匹配項。

參考文獻:

搜索 http://www.w3schools.com/jsref/jsref_obj_regexp.asp

搜索 「X(= Y?)」 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

4

閥塊Mr_Green's answer到官能編程風格,以避免使用 「= N?」臨時全局變量。

var matches = string2.split('[') 
    .filter(function(v){ return v.indexOf(']') > -1}) 
    .map(function(value) { 
    return value.split(']')[0] 
    }) 
1

簡單的解決方案

注意:該解決方案用於字符串只具有單一的 「(」 和 「)」 想在這個問題字符串。

("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop(); 

Online demo (jsfiddle)

相關問題