Here RegEx was needed to capture all the contents between (but not including the "{" and "}") of the first "{" and the last "}", that is, the pair "{}" may still appear in the text, RegEx is needed under JS, you can if I somehow do it, I just found how to do it between "{" and "}, but I don’t understand how between the extreme" {"and"} ".
1 answer
JavaScript regular expressions cannot specify the s ( DOTALL ) modifier , so you can use [^] to capture any character, any character other than the empty string .
Since in other languages this pattern causes an error, it is customary to use cross-platform equivalents: [^] = [\s\S] = [\d\D] = [\w\W] . The most commonly used is [\s\S] .
To capture text from the first { to the last } , a greedy quantifier *, zero and more repetitions is needed.
var s = "Текст до скобки {\nСтрока 1: {123},{456}\nСтрока 2: {Ещё текст: {...}}\r\n}"; console.log(s); // Как выглядит строка var m = s.match(/{([^]*)}/); if (m) { // Было ли найдено совпадение? console.log("'", m[1], "'"); // Если да, получить значение первой группы } However, it is easier in this case to use string methods (code without error handling):
var s = "Текст до скобки {\nСтрока 1: {123},{456}\nСтрока 2: {Ещё текст: {...}}\r\n}"; s = s.substring(s.indexOf("{")+1,s.lastIndexOf("}")); console.log(s); - And for some more
[\s\S\n]... - Qwertiy ♦ - Rather,
[\s\S\r]- in Visual Studio. In Vim, in general, their troubles. - Wiktor Stribiżew - Yes, I'm talking about VS. - Qwertiy ♦
- If there were more such detailed answers, then RegEx is not my strong point, because it is rarely needed, and by the time you need it again, you already forget that you managed to study it last time, and the differences JS / pcre are constantly confusing. - pnp2000
- oneJS regular expressions are very different from PCRE. Okay, modifiers (there are only three in JS), optional exciting groups in JS that have not found a match, are always different from null, unlike PCRE, backlinks followed by a digit in the replacement lines for JS can be defined as, for example,
$10(=$1+0), whereas in PCRE${1}0. And I’m generally silent about handling zero-length matches, JS doesn’t cope at all by itself, it’s often necessary to fix the template and add the code. - Wiktor Stribiżew
|
/\{([\s\S]*)\}/take the result from the first group. - Visman