RegEx从方括号内获取文本[复制]

时间:2022-07-20 21:43:19

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

我正在尝试用/\[(.*?)\]/g来做这个,但是我没有得到满意的结果,我得到了括号内的单词,但也不是我想要的括号。

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

我搜索一些类似的问题,但这些解决方案正常工作对我来说这是一个什么发现(? < = \[[^]])+(? = \])在RegEx教练工作但不使用javascript。这是我得到的折射

here is what i have done so far demo

这是我到目前为止所做的演示

please help

请帮助

2 个解决方案

#1


23  

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:

但在一般情况下,exec或基于替换的循环会导致更简单的代码:

words = []
a.replace(/\[(.+?)\]/g, function($0, $1) { words.push($1) })

#2


5  

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

这个小提琴使用RegExp。只输出括号内的内容。

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])
}

#1


23  

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:

但在一般情况下,exec或基于替换的循环会导致更简单的代码:

words = []
a.replace(/\[(.+?)\]/g, function($0, $1) { words.push($1) })

#2


5  

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

这个小提琴使用RegExp。只输出括号内的内容。

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])
}