简体   繁体   English

正则表达式匹配花括号

[英]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/ 我也开始了这个小提琴, http://jsfiddle.net/rgy3y/1/

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}'. 这样做的好处是,如果arr包含类似'{1}'的字符串,则不会发生任何奇怪的事情。 Eg 例如
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}' stringFormat('{0}', ['{1}', 'foo']) === '{1}'一致而不是'foo'与原始的固定版本一样,但与stringFormat('{1}', ['foo', '{0}']) === '{0}'不一致stringFormat('{1}', ['foo', '{0}']) === '{0}'

To get a \\ in a string literal you need to type \\\\ . 要在字符串文字中获取\\ ,您需要输入\\\\ In particular, '\\{' == '{' . 特别是'\\{' == '{' You want '\\\\{' . 你想要'\\\\{'

Not familiar with javascript (or whatever) regex, but you are only matching expressions that contain only { X } (or only lines with that expression, again depending on your regex). 不熟悉javascript(或其他)正则表达式,但您只匹配仅包含{ X }的表达式(或仅包含该表达式的行,同样取决于您的正则表达式)。
' ^ {' + i + '} $ ' ' ^ {'+ i +'} $ '

Remove the ^ and $. 删除^和$。

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

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