Javascript 正则表达式从方括号内获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11013110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx to get text from inside the square brackets
提问by sohaan
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 refrencefrom where i got this
我确实在 SO 上搜索了一些类似类型的问题,但这些解决方案对我来说都没有正常工作,这是一个(?<=\[)[^]]+(?=\])
在 RegEx Coach 中发现但不适用于 javascript 的解决方案。这是我从哪里得到这个的参考
here is what i have done so far demo
这是我到目前为止所做的演示
please help
请帮忙
回答by georg
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
orreplace
基于循环会导致更简单的代码:
words = []
a.replace(/\[(.+?)\]/g, function(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])
}
, ) { words.push() })
回答by Sindri Guemundsson
This fiddleuses RegExp.execand outputs only what's inside the parenthesis.
这个小提琴使用RegExp.exec并只输出括号内的内容。
##代码##