Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching curly bracket

Looking for help in matching the curly brackets in a regular expression pattern. I've tried different combinations of escapes, and symbol matching with little luck. Perhaps because it's Friday afternoon and I'm overlooking something; but your ideas would be greatly appreciated. The code below:

function stringFormat(str, arr) {
   for (var i = 0; i < arr.length; i++) {
        var regExp = new RegExp('^\{' + i + '\}$', 'g');
        str = str.replace(regExp, arr[i]);   
    }
    return str;  
}

var str = '<p>The quick {0}, brown {1}</p>';

$('#test').html(stringFormat(str, ['brown', 'fox']));

I've also started a fiddle on this, http://jsfiddle.net/rgy3y/1/

like image 761
gnome Avatar asked Mar 25 '11 20:03

gnome


People also ask

How do you match curly brackets in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.

What is {} in regular expression?

Integer values enclosed in {} indicate the number of times to apply the preceding regular expression. n is the minimum number, and u is the maximum number. If you specify only n, it indicates the exact number of times to apply the regular expression.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What are {} used for?

Brackets are used to insert explanations, corrections, clarifications, or comments into quoted material. Brackets are always used in pairs; you must have both an opening and a closing bracket.


2 Answers

Instead of trying to match a bunch of different numbers, why not just do it all in one fell swoop:

function stringFormat(str, arr) {
  return str.replace(
      /\{([0-9]+)\}/g,
      function (_, index) { return arr[index]; });
}

On your example,

var str = '<p>The quick {0}, brown {1}</p>';

// Alerts <p>The quick brown, brown fox</p>
alert(stringFormat(str, ['brown', 'fox']));

This has the benefit that nothing weird will happen if arr contains a string like '{1}'. E.g.
stringFormat('{0}', ['{1}', 'foo']) === '{1}' consistently instead of 'foo' as with the fixed version of the original, but inconsistently with stringFormat('{1}', ['foo', '{0}']) === '{0}'

like image 60
Mike Samuel Avatar answered Sep 18 '22 12:09

Mike Samuel


To get a \ in a string literal you need to type \\. In particular, '\{' == '{'. You want '\\{'.

like image 43
Laurence Gonsalves Avatar answered Sep 17 '22 12:09

Laurence Gonsalves