简体   繁体   中英

Getting text enclosed by curly brackets that also contain curly brackets in javascript

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?

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]

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM