Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to get text from inside the square brackets [duplicate]

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.

like image 606
sohaan Avatar asked Jun 13 '12 10:06

sohaan


People also ask

How do you match a square bracket in regex?

You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

What does bracket do in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

What is Slash's regex?

The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.


2 Answers

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) })
like image 104
georg Avatar answered Nov 12 '22 16:11

georg


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])
}
like image 35
Sindri Guðmundsson Avatar answered Nov 12 '22 15:11

Sindri Guðmundsson