我在寻找regexp以获取大括号之间的值,但是在internet上找到的示例仅限于一个子字符串,而我需要获得与模式匹配的所有子字符串值。例:
The {Name_Student} is living in {City_name}如果可能,如何在大括号({})之间,在数组中获取子字符串的值!我正试图在javascript中实现这一点。
(预先谢谢:)
发布于 2014-07-17 09:35:57
匹配值,然后删除curlys:
str.match(/\{.+?\}/g).map(function(x){return x.slice(1,-1)})或者您可以通过捕获组来完成这一任务:
var res = []
str.replace(/\{(.+?)\}/g, function(_, m){res.push(m)})发布于 2014-07-17 09:35:04
regex {([^}]+)}捕获到组1的所有匹配项(请参见regex演示右窗格中的捕获)。下面的代码检索它们。
In JavaScript
var the_captures = [];
var yourString = 'your_test_string'
var myregex = /{([^}]+)}/g;
var thematch = myregex.exec(yourString);
while (thematch != null) {
// add it to array of captures
the_captures.push(thematch[1]);
document.write(thematch[1],"<br />");
// match the next one
thematch = myregex.exec(yourString);
}解释
{与开口大括号匹配([^}]+)捕获所有不是组1结束大括号的字符}与结束大括号匹配发布于 2014-07-17 09:33:57
下面的regex将把大括号内的值捕获到第一个组中。
\{([^}]*)\}演示
https://stackoverflow.com/questions/24799778
复制相似问题