[javascript] Regex to get string between curly braces

Unfortunately, despite having tried to learn regex at least one time a year for as many years as I can remember, I always forget as I use them so infrequently. This year my new year's resolution is to not try and learn regex again - So this year to save me from tears I'll give it to Stack Overflow. (Last Christmas remix).

I want to pass in a string in this format {getThis}, and be returned the string getThis. Could anyone be of assistance in helping to stick to my new year's resolution?


Related questions on Stack Overflow:

This question is related to javascript regex

The answer is


Try this:

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

For example

Welcome to RegExr v2.1 by #{gskinner.com},  #{ssd.sd} hosted by Media Temple!

will return gskinner.com, ssd.sd.


Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

This one works in Textmate and it matches everything in a CSS file between the curly brackets.

\{(\s*?.*?)*?\}

selector {. . matches here including white space. . .}

If you want to further be able to return the content, then wrap it all in one more set of parentheses like so:

\{((\s*?.*?)*?)\}

and you can access the contents via $1.

This also works for functions, but I haven't tested it with nested curly brackets.


Regex for getting arrays of string with curly braces enclosed occurs in string, rather than just finding first occurrence.

 /\{([^}]+)\}/gm 

This one matches everything even if it finds multiple closing curly braces in the middle:

\{([\s\S]*)\}

Example:

{
  "foo": {
    "bar": 1,
    "baz": 1,
  }
}

You want to use regex lookahead and lookbehind. This will give you only what is inside the curly braces:

(?<=\{)(.*?)(?=\})

This one works in Textmate and it matches everything in a CSS file between the curly brackets.

\{(\s*?.*?)*?\}

selector {. . matches here including white space. . .}

If you want to further be able to return the content, then wrap it all in one more set of parentheses like so:

\{((\s*?.*?)*?)\}

and you can access the contents via $1.

This also works for functions, but I haven't tested it with nested curly brackets.


Try

/{(.*?)}/

That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.

Another way would be

/{([^}]*)}/

This matches any character except a } char (another way of not being greedy)


You can use this regex recursion to match everythin between, even another {} (like a JSON text) :

\{([^()]|())*\}

Try

/{(.*?)}/

That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.

Another way would be

/{([^}]*)}/

This matches any character except a } char (another way of not being greedy)


/\{([^}]+)\}/

/        - delimiter
\{       - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
(        - start capturing
[^}]     - character class consisting of
    ^    - not
    }    - a closing brace (no escaping necessary because special characters in a character class are different)
+        - one or more of the character class
)        - end capturing
\}       - the closing literal brace
/        - delimiter

Try this one, according to http://www.regextester.com it works for js normaly.

([^{]*?)(?=\})


Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

Even this helps me while trying to solve someone's problem,

Split the contents inside curly braces ({}) having a pattern like, {'day': 1, 'count': 100}.

For example:

#include <iostream> 
#include <regex> 
#include<string> 
using namespace std; 

int main() 
{ 
    //string to be searched
    string s = "{'day': 1, 'count': 100}, {'day': 2, 'count': 100}";

    // regex expression for pattern to be searched 
    regex e ("\\{[a-z':, 0-9]+\\}");
    regex_token_iterator<string::iterator> rend;

    regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
    while (a!=rend) cout << " [" << *a++ << "]";
    cout << endl;

    return 0; 
}

Output:

[{'day': 1, 'count': 100}] [{'day': 2, 'count': 100}]

i have looked into the other answers, and a vital logic seems to be missing from them . ie, select everything between two CONSECUTIVE brackets,but NOT the brackets

so, here is my answer

\{([^{}]+)\}

/\{([^}]+)\}/

/        - delimiter
\{       - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
(        - start capturing
[^}]     - character class consisting of
    ^    - not
    }    - a closing brace (no escaping necessary because special characters in a character class are different)
+        - one or more of the character class
)        - end capturing
\}       - the closing literal brace
/        - delimiter

Try this:

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

For example

Welcome to RegExr v2.1 by #{gskinner.com},  #{ssd.sd} hosted by Media Temple!

will return gskinner.com, ssd.sd.


Try

/{(.*?)}/

That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.

Another way would be

/{([^}]*)}/

This matches any character except a } char (another way of not being greedy)


/\{([^}]+)\}/

/        - delimiter
\{       - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
(        - start capturing
[^}]     - character class consisting of
    ^    - not
    }    - a closing brace (no escaping necessary because special characters in a character class are different)
+        - one or more of the character class
)        - end capturing
\}       - the closing literal brace
/        - delimiter

var re = /{(.*)}/;
var m = "{helloworld}".match(re);
if (m != null)
    console.log(m[0].replace(re, '$1'));

The simpler .replace(/.*{(.*)}.*/, '$1') unfortunately returns the entire string if the regex does not match. The above code snippet can more easily detect a match.


i have looked into the other answers, and a vital logic seems to be missing from them . ie, select everything between two CONSECUTIVE brackets,but NOT the brackets

so, here is my answer

\{([^{}]+)\}

/\{([^}]+)\}/

/        - delimiter
\{       - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
(        - start capturing
[^}]     - character class consisting of
    ^    - not
    }    - a closing brace (no escaping necessary because special characters in a character class are different)
+        - one or more of the character class
)        - end capturing
\}       - the closing literal brace
/        - delimiter

This one matches everything even if it finds multiple closing curly braces in the middle:

\{([\s\S]*)\}

Example:

{
  "foo": {
    "bar": 1,
    "baz": 1,
  }
}

Try this

let path = "/{id}/{name}/{age}";
const paramsPattern = /[^{\}]+(?=})/g;
let extractParams = path.match(paramsPattern);
console.log("extractParams", extractParams) // prints all the names between {} = ["id", "name", "age"]

Even this helps me while trying to solve someone's problem,

Split the contents inside curly braces ({}) having a pattern like, {'day': 1, 'count': 100}.

For example:

#include <iostream> 
#include <regex> 
#include<string> 
using namespace std; 

int main() 
{ 
    //string to be searched
    string s = "{'day': 1, 'count': 100}, {'day': 2, 'count': 100}";

    // regex expression for pattern to be searched 
    regex e ("\\{[a-z':, 0-9]+\\}");
    regex_token_iterator<string::iterator> rend;

    regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
    while (a!=rend) cout << " [" << *a++ << "]";
    cout << endl;

    return 0; 
}

Output:

[{'day': 1, 'count': 100}] [{'day': 2, 'count': 100}]

var re = /{(.*)}/;
var m = "{helloworld}".match(re);
if (m != null)
    console.log(m[0].replace(re, '$1'));

The simpler .replace(/.*{(.*)}.*/, '$1') unfortunately returns the entire string if the regex does not match. The above code snippet can more easily detect a match.


Try this

let path = "/{id}/{name}/{age}";
const paramsPattern = /[^{\}]+(?=})/g;
let extractParams = path.match(paramsPattern);
console.log("extractParams", extractParams) // prints all the names between {} = ["id", "name", "age"]

Regex for getting arrays of string with curly braces enclosed occurs in string, rather than just finding first occurrence.

 /\{([^}]+)\}/gm 

You want to use regex lookahead and lookbehind. This will give you only what is inside the curly braces:

(?<=\{)(.*?)(?=\})

Try

/{(.*?)}/

That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.

Another way would be

/{([^}]*)}/

This matches any character except a } char (another way of not being greedy)