好的,我有以下字符串,
var str = 'some text {Foo} some more text {9}';
现在我知道如何替换特定的字符/单词,
var newStr = str.replace(/{Foo}/g, 'bar');
但如果数字可以是任何数字,我将如何替换{9}?
答案 0 :(得分:4)
您可以将元序列用于数字\d
。
var str = 'some text {Foo} some more text {9}',
newStr = str.replace(/{\d+}/g, 'bar');
console.log(newStr);
答案 1 :(得分:1)
您应该使用\{/d+}/g
正则表达式匹配任何数字:
\d
元字符匹配数字+
量词表示匹配类型中的一个或多个/g
修饰符表示执行全局匹配
var str = 'some text {Foo} some more text {9}';
var newstr = str.replace(/{\d+}/g, 'number');
console.log(newstr);
str = 'some text {Foo} some more text {99199} and {435}';
newstr = str.replace(/\d+/g, 'number');
console.log(newstr);

顺便说一句,我使用this tool来测试我的正则表达式,如果你想尝试更多正则表达式,可能会派上用场。
答案 2 :(得分:1)
你没有指定什么是“数字”,所以我设计了一个解决方案,不仅适用于正整数,还适用于有符号整数和浮点数,并负责嵌套括号。
/{\d+}/g
匹配大括号内的一个或多个数字
var str = 'some text {Foo} some more text {9}';
var m = str.match(/{\d+}/g);
console.log(m); // m = [ "{9}" ]
但上述模式与浮点数不匹配,例如{3.14}
str = 'some text {Foo} some more text {9} and {3.14}';
m = str.match(/{\d+}/g);
console.log(m); // m = [ "{9}" ]
那么双括号怎么样呢?
str = 'some text {Foo} some more text {9} and {3.14} and {{8}}';
m = str.match(/{\d+}/g);
console.log(m); // m = [ "{9}", "{8}" ]
您可以使用它来匹配浮动
str = 'some text {Foo} some more text {9} and {3.14} and {{8}}';
m = str.match(/{(\-|\+)?(\d+(\.\d+)?)}/g);
console.log(m); // m = [ "{9}", "{3.14}", "{8}" ]
所以这是一个允许嵌套花括号的解决方案
str = 'some text {Foo} some more text {9} and {3.14} and {{8}}';
var newStr = str.replace(/{(\-|\+)?(\d+(\.\d+)?)}/g, '{NUMBER}');
console.log(newStr);
处理嵌套括号
匹配花括号之间的所有内容并检查数值(正则表达式来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)
str = 'some text {Foo} some more text {9} and {3.14} and {{8}}';
m = str.match(/{.+?}/g);
console.log(m); // m = [ "{Foo}", "{9}", "{3.14}", "{{8}" ]
for (var i = 0; i < m.length; i++) {
mi = m[i];
value = mi.slice(1, mi.length - 1);
// regular expression for parsing floats from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?)$/
.test(value)) {
console.log("matches a number: ", value);
}
};
编写一个仅替换数值的函数
function replaceNumber(string, repl) {
return string.replace(/{.+?}/g, function(match) {
value = match.slice(1, match.length - 1);
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?)$/
.test(value)) {
return '{' + repl + '}';
} else {
return match;
}
});
}
str = 'some text {Foo} some more text {9} and {3.14} and {{8}} and {-2}';
newStr = replaceNumber(str, 'NUMBER');
console.log(newStr);
// newStr = some text {Foo} some more text {NUMBER} and {NUMBER} and {{8}} and {NUMBER}