0

I'm trying to extract some data from a large string and I was wondering if it is possible to use regexp. Currently, I'm using javascript. For example:

This is some [example] text for my javascript [regexp] [lack] of knowledge.

With this string, I would like to generate a JSON array with the texts that are between the square brackets.

example, regexp, lack

I hope someone can help me do this in a simple way so I can understand how it works. Thank you in advance for your help. Daniel!

2
  • 2
    Have you even tried to solve it by yourself? It's a trivial regex task. Commented Mar 7, 2014 at 2:50
  • "so i can understand how it works" --- regular expressions (and mostly everything in programming) requires reading, not just mimicing other people code. Otherwise you will be in stuck as soon as you see something that slightly different from what you "know" (actually it barely can be called "knowledge") Commented Mar 7, 2014 at 2:51

3 Answers 3

4
var str = "This is some [example] text for my javascript [regexp] [lack] of knowledge."
var regex = /\[(.*?)\]/g, result, indices = [];
while ( (result = regex.exec(str)) ) {
    indices.push(result[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

2
var text = 'some [example] text for my javascript [regexp] [lack] of knowledge.';
text.match(/\[(.*?)\]/g).map(function(m) {
    return m.substr(1, m.length - 2);
})
// => ["example", "regexp", "lack"]

2 Comments

thank you very much falsetru, this works great, can you please tell me what (.*?) means
@PacuraruDaniel, . matches any character. * mean that previous pattern (. here) should match 0 or more times. By default .* is greedy (matches as much as possible) Without ?, it matches [example ] text for ... lack]. By appending ?, it works non-greedy fashion.
1

http://jsfiddle.net/mE7EQ/

I wrote one up real quick, if you have any questions about it, let me know!

var a = 'This is some [example] text for my javascript [regexp] [lack] of knowledge.'
var results = a.match(/\[\w*\]/g);

alert(results[0] + ' ' + results[1] + ' ' + results[2]);

2 Comments

thank you very much for this, it works exactly as i wanted to
you are welcome! I would recommend reading up on stuff though in the future, esp on how regex work. It is well worth learning, and will serve you well! Teach a man to fish, and he will feed himself, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.