简体   繁体   English

匹配括号之间的所有内容

[英]match everything between brackets

I need to match the text between two brackets. 我需要在两个方括号之间匹配文本。 many post are made about it but non are supported by JavaScript because they all use the lookbehind. 关于它的文章很多,但JavaScript不支持,因为它们都使用了后向功能。 the text is as followed 案文如下

"{Code} - {Description}" “ {代码}-{说明}”

I need Code and Description to be matched with out the brackets the closest I have gotten is this 我需要代码和描述与括号最匹配,这是我得到的

 /{([\s\S]*?)(?=})/g

leaving me with "{Code" and "{Description" and I followed it with doing a substring. 给我留下“ {Code”和“ {Description”,然后我做一个子字符串。

so... is there a way to do a lookbehind type of functionality in Javascript? 那么...有没有办法在Javascript中进行后备功能类型?

Use it as: 用作:

input = '{Code} - {Description}';
matches = [], re = /{([\s\S]*?)(?=})/g;

while (match = re.exec(input)) matches.push(match[1]);

console.log(matches);
["Code", "Description"]

You could simply try the below regex, 您可以尝试以下正则表达式,

[^}{]+(?=})

Code: 码:

> "{Code} - {Description}".match(/[^}{}]+(?=})/g)
[ 'Code', 'Description' ]

Actually, in this particular case, the solution is quite easy: 实际上,在这种情况下,解决方案非常简单:

s = "{Code} - {Description}"
result = s.match(/[^{}]+(?=})/g) // ["Code", "Description"]

Have you tried something like this, which doesn't need a lookahead or lookbehind: 您是否尝试过类似的操作,而无需先行或后行:

{([^}]*)}

You would probably need to add the global flag, but it seems to work in the regex tester . 您可能需要添加全局标志,但是它似乎可以在regex测试器中使用

The real problem is that you need to specify what you want to capture, which you do with capture groups in regular expressions. 真正的问题是您需要指定要捕获的内容,这需要使用正则表达式中的捕获组来完成。 The part of the matched regular expression inside of parentheses will be the value returned by that capture group . 括号内匹配的正则表达式部分将是该捕获组返回的值。 So in order to omit { and } from the results, you just don't include those inside of the parentheses. 因此,为了从结果中省略{} ,您只需要在括号内不包括那些即可。 It is still necessary to match them in your regular expression, however. 但是,仍然需要在正则表达式中匹配它们。

You can see how to get the value of capture groups in JavaScript here . 您可以在此处查看如何获取JavaScript中捕获组的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM