我有一个包含文本字符串的textarea,我将其值传递给名为updatestring
的变量。我收到的文字区域中的文字被update(){
和}
括起来了。本文进入变量updatecode。
var updatestring = 'update(){\n//logic code here...\n\n\n}\n' ;
var updatecode = updatestring.match(/update\(\)\{([^}]+)\}/)[1];
我遇到的问题是,我希望update(){
和}
所包含的文字也包含字符}
。在JavaScript中,有没有简单的方法可以在不使用库的情况下执行此操作?
答案 0 :(得分:2)
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]
答案 1 :(得分:2)
贪婪匹配(这是*
的默认行为)将跳过中间}
个字符直到最后一个字符,因此不需要任何特殊内容:
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);

[^]
将匹配包括换行符在内的所有内容。
顺便说一下,为什么要尝试使用regexp解析看起来像JavaScript的东西?