0

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?

Jose Rivas
  • 59
  • 1
  • 1
  • 9
  • This is not a duplicate - the OP _knows_ how to extract stuff, their question is how do that without matching delimiters as well. – georg Sep 17 '14 at 14:22
  • Something unclear with your question: could code and description include newlines or anything else ? With your exemple this should be enought `/{(.*?)}/g` and parse the matches to get the capturing groups instead of the whole match see [THIS](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression). – Tensibai Sep 17 '14 at 14:25
  • @georg it is a kind of duplicate. He seems not to know how to get the capturing group instead of the whole match. – Tensibai Sep 17 '14 at 14:26

4 Answers4

1

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"]
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You could simply try the below regex,

[^}{]+(?=})

Code:

> "{Code} - {Description}".match(/[^}{}]+(?=})/g)
[ 'Code', 'Description' ]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

Actually, in this particular case, the solution is quite easy:

s = "{Code} - {Description}"
result = s.match(/[^{}]+(?=})/g) // ["Code", "Description"]
georg
  • 211,518
  • 52
  • 313
  • 390
0

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.

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109