Reputation: 2450
I have a textarea that contains a text string, I am getting its value to a variable named updatestring
. I am getting the text in this text area that's enclosed by update(){
and }
. This text goes into the variable updatecode.
var updatestring = 'update(){\n//logic code here...\n\n\n}\n' ;
var updatecode = updatestring.match(/update\(\)\{([^}]+)\}/)[1];
The problem I have is that I want to be possible that the text enclosed by update(){
and }
also contain the character }
. In JavaScript, is there any easy way to do this without using a library?
Upvotes: 0
Views: 68
Reputation: 7388
Edit: torazaburo's answer is better, but I'll leave this here to show another way just for educational purposes. ;)
Try this: /[^{]*{((?:.|\r|\n)*)}/
Example: https://regex101.com/r/QOIyvz/4
[^{]*
- skips all characters until {
is found and stops just before it.
{
- matches the first brace.
((?:.|\r|\n)*)
- ?:
starts a non-capturing group (will not be returned), and *
"greedily" matches all characters and carriage return and line feeds, and makes them all part of a captured group (between the other (
and )
) that is returned.
}
- Regex will stop the greedy search to match the last one found.
Example: updatestring.match(/[^{]*{((?:.|\r|\n)*)}/)[1]
Upvotes: 2
Reputation:
Greedy matching (which is the default behavior of *
) will skip over the intermediate }
characters up to the last one, so nothing special is needed:
var updatestring = 'update(){\n//logic {embedded curly brackets}code here...\n\n\n}\n' ;
var regexp = /{([^]*)}/;
// ^ match starting curly
// ^^^^^^ capture
// ^^^ any character including newline
// ^ any number of times
// ^ match ending curly
var regexp = result = updatestring.match(regexp)[1];
console.log(updatestring, result);
The [^]
will match everything including newlines.
By the way, why are you trying to parse something that looks like JavaScript using regexp?
Upvotes: 2