简体   繁体   中英

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. 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.

so... is there a way to do a lookbehind type of functionality in 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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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