RegEx to get text from inside the square brackets

2020-06-03 06:32发布

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 refrence from where i got this

here is what i have done so far demo

please help

2条回答
▲ chillily
2楼-- · 2020-06-03 07:15

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) })
查看更多
仙女界的扛把子
3楼-- · 2020-06-03 07:20

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])
}
查看更多
登录 后发表回答