Javascript 正则表达式匹配大括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5437694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:12:10  来源:igfitidea点击:

Regex matching curly bracket

javascriptregex

提问by gnome

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/

回答by Mike Samuel

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 arrcontains 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}'

这样做的好处是,如果arr包含像“{1}”这样的字符串,则不会发生任何奇怪的事情。例如,与原始版本的固定版本
stringFormat('{0}', ['{1}', 'foo']) === '{1}'一致而不是一致'foo',但与stringFormat('{1}', ['foo', '{0}']) === '{0}'

回答by Laurence Gonsalves

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

\在字符串文字中获取 a ,您需要输入\\. 特别是'\{'== '{'。你要'\\{'

回答by unexpectedvalue

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).
'^{' + i + '}$'

不熟悉 javascript(或其他)正则表达式,但您只匹配仅包含 { X} 的表达式(或仅包含该表达式的行,再次取决于您的正则表达式)。
' ^{' + i + '} $'

Remove the ^ and $.

删除 ^ 和 $。