javascript, regex parse string content in curly brackets
Asked Answered
L

6

21

i am new to regex. I am trying to parse all contents inside curly brackets in a string. I looked up this post as a reference and did exactly as one of the answers suggest, however the result is unexpected.

Here is what i did

var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/
regex.exec(abc) // i got ["{string1}", "string1"]
             //where i am expecting ["string1", "string2"]

i think i am missing something, what am i doing wrong?

update

i was able to get it with /g for a global search

var regex = /{(.*?)}/g
abc.match(regex) //gives ["{string1}", "{string2}"]

how can i get the string w/o brackets?

Lido answered 20/3, 2012 at 18:2 Comment(0)
M
32
"test/abcd{string1}test{string2}test".match(/[^{}]+(?=\})/g)

produces

["string1", "string2"]

It assumes that every } has a corresponding { before it and {...} sections do not nest. It will also not capture the content of empty {} sections.

Manion answered 20/3, 2012 at 18:9 Comment(5)
This is good. But you do not need to escape the closing brace. /[^{}]+(?=})/gAnkus
How do the same with this braces? [ ]Lanchow
@AuthorProxy, to include [ or ] in a character set, escape them. [\[\]] is a character set with only the square brackets.Manion
@MikeSamuel it doesn't work, check at any online regexpLanchow
@Lanchow I did. /[\[\]]+/.exec('a[[]]b')[0] === '[[]]' is true in JS.Manion
U
3
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g
var matches;

while(matches = regex.exec(abc))
    console.log(matches);
Utta answered 20/3, 2012 at 18:9 Comment(0)
G
2

Try this:

var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g //g flag so the regex is global
abc.match(regex) //find every match

a good place to read about Regex in javascript is here, and a nice place to test is here

good luck!

Gains answered 20/3, 2012 at 18:6 Comment(2)
I don't think g would make a difference here. It is not getting the second match (string2) because it is calling exec only once.Ankus
@Ankus you're right, but I called match, and without the g, it will return ["{string1}", "string1"]Gains
S
1

This result:

["{string1}", "string1"]

is showing you that for the first match, the entire regex matched "{string1}" and the first capturing parentheses matched "string1".

If you want to get all matches and see all capturing parens of each match, you can use the "g" flag and loop through, calling exec() multiple times like this:

var abc = "test/abcd{string1}test{string2}test"; //any string
var regex = /{(.+?)}/g;
var match, results = [];
while (match = regex.exec(abc)) {
    results.push(match[1]);   // save first captured parens sub-match into results array
}

// results == ["string1", "string2"]

You can see it work here: http://jsfiddle.net/jfriend00/sapfm/

Spinode answered 20/3, 2012 at 18:5 Comment(3)
assignment in a condition... not my cup of tea.Trichome
It's an efficient way to do this type of loop and somewhat common for this exact purpose. I would generally avoid it too, except in this type of case. You can take a couple more lines of code to accomplish the same thing without it if you want.Spinode
thanks for the explanation, i was wondering why the same string appeared twice. thank you!Lido
B
1

Nothing wrong. But you'll need to look at your capturing groups (the second element in the array) to get the content you wanted (you can ignore the first). To get all occurences, it's not enough to run exec once, you'll need to loop over the results using match.

Edit: nevermind that, afaik you can't access capturing groups with match. A simpler solution would be using a positive lookahead, as Mike Samuel suggested.

Battiste answered 20/3, 2012 at 18:7 Comment(0)
M
1

try this for file

const fs = require('fs');

fs.readFile('logs.txt', function(err, data) {
if(err) throw err;
const paragraph = "'" + data + "'";
const regex = /\d+\<;>\S+\<;>(\d+)\<;/g;
const found = paragraph.match(regex);

console.log(found);
})
Maice answered 8/12, 2021 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.