10

Possible Duplicate:
Regular Expression to find a string included between two characters, while EXCLUDING the delimiters

I have a function where I have to get text which is enclosed in square brackets but not brackets for example

this is [test] line i [want] text [inside] square [brackets]

from the above line I want words:

test
want
inside
brackets

I am trying with to do this with /\[(.*?)\]/g but I am not getting satisfied result, I get the words inside brackets but also brackets which are not what I want

I did search for some similar type of question on SO but none of those solution work properly for me here is one what found (?<=\[)[^]]+(?=\]) this works in RegEx coach but not with JavaScript. Here is reference from where I got this

here is what I have done so far: demo

please help.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
sohaan
  • 261
  • 1
  • 4
  • 9
  • its not exact duplicate square bracket in not a normal character it has to be dealt differently then other characters – sohaan Jun 13 '12 at 11:11

2 Answers2

30

A single lookahead should do the trick here:

 a = "this is [test] line i [want] text [inside] square [brackets]"
 words = a.match(/[^[\]]+(?=])/g)

but in a general case, exec or replace-based loops lead to simpler code:

words = []
a.replace(/\[(.+?)\]/g, function($0, $1) { words.push($1) })
georg
  • 211,518
  • 52
  • 313
  • 390
6

This fiddle uses RegExp.exec and outputs only what's inside the parenthesis.

var data = "this is [test] line i [want] text [inside] square [brackets]"
var re= /\[(.*?)\]/g;
for(m = re.exec(data); m; m = re.exec(data)){
    alert(m[1])
}
Sindri Guðmundsson
  • 1,253
  • 10
  • 24
  • Sir can you please explain me what is happening in for loop and can we use underscore.js 's _each() function to iterate – sohaan Jun 13 '12 at 11:06