javascript - 正則表達式地址 - 正則表達式括號
正則表達式來獲得Javascript中括號之間的字符串 (4)
解決方案簡單
注意 :這個解決方案用於在這個問題中只有單個“(”和“)”字符串的字符串。
("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();
我想寫一個正則表達式,它返回一個括號之間的字符串。 例如:我想獲取位於字符串“(”和“)”之間的字符串
I expect five hundred dollars ($500).
會返回
$500
找到正則表達式來獲取Javascript中兩個字符串之間的字符串
但我是新的正則表達式。 我不知道如何在正則表達式中使用'(',')'
嘗試字符串操作:
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]);
}
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));
}
您需要創建一組轉義(帶括號)括號(與括號匹配)和一組創建捕獲組的常規括號:
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的視覺解釋
為了避免使用臨時全局變量,將Mr_Green的答案移植到函數式編程風格上。
var matches = string2.split('[')
.filter(function(v){ return v.indexOf(']') > -1})
.map( function(value) {
return value.split(']')[0]
})