[英]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
. 我有一个包含文本字符串的textarea,我将其值获取到名为
updatestring
的变量。 I am getting the text in this text area that's enclosed by update(){
and }
. 我正在此文本区域中获得由
update(){
和}
包围的文本。 This text goes into the variable updatecode. 此文本进入变量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 }
. 我的问题是,我希望有可能
update(){
和}
包含的文本也包含}
字符。 In JavaScript, is there any easy way to do this without using a library? 在JavaScript中,有没有不使用库就可以做到这一点的简便方法?
Edit: torazaburo 's answer is better, but I'll leave this here to show another way just for educational purposes. 编辑: torazaburo的答案更好,但是我将在这里留出这仅仅是为了教育目的而显示另一种方式。 ;)
;)
Try this: /[^{]*{((?:.|\\r|\\n)*)}/
试试这个:/[
/[^{]*{((?:.|\\r|\\n)*)}/
:.| /[^{]*{((?:.|\\r|\\n)*)}/
Example: https://regex101.com/r/QOIyvz/4 例如: 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. ((?:.|\\r|\\n)*)
- ?:
启动非捕获组(恕不退还)和*
“贪婪”匹配所有的字符,回车和换行,并使其所有部分返回的捕获组中的一个(在另一个(
和之间)
。
}
- 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? 顺便说一句,为什么要尝试使用regexp解析类似于JavaScript的内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.