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.
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): [][] .
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.
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.
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) })
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])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With