正则表达式从方括号内获取文本 [英] RegEx to get text from inside the square brackets

查看:94
本文介绍了正则表达式从方括号内获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用正则表达式查找介于两个字符,但不包括定界符

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]

我想在上面一行

测试

想要

内部

括号

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

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

我确实在SO上搜索了某种类似类型的问题,但这些解决方案都无法对我正常工作,这是在RegEx coach中可以找到(?<=\[)[^]]+(?=\])的一种方法,但不适用于javascript.这是引用,我从哪里获得的

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

请帮助

推荐答案

在这里先行一步即可解决问题:

A single lookahead should do the trick here:

 a = "this is [test] line i [want] text [inside] square [brackets]"
 words = a.match(/[^[\]]+(?=])/g)

,但是在一般情况下,基于execreplace的循环会导致代码更简单:

but in a general case, exec or replace-based loops lead to simpler code:

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

这篇关于正则表达式从方括号内获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆