如何使用正则表达式执行此操作,将每个字符串替换为!
包含在函数中的函数:
例子:
3!
=>fact(3)
2.321!
=>fact(2.321)
(3.2+1)!
=>fact(3.2+1)
(sqrt(2)+2/2^2)!
=>fact(sqrt(2)+2/2^2)
如何使用正则表达式执行此操作,将每个字符串替换为!
包含在函数中的函数:
例子:
3!
=>fact(3)
2.321!
=>fact(2.321)
(3.2+1)!
=>fact(3.2+1)
(sqrt(2)+2/2^2)!
=>fact(sqrt(2)+2/2^2)
Given your examples, you don't need a regex at all:
var s = "3!"; //for example
if (s[s.length-1] === "!")
s = "fact(" + s.substr(0, s.length-1) + ")";
Not doubling the parentheses for the last case just requires another test:
var s = "(sqrt(2)+2/2^2)!"; //for example
if (s[s.length-1] === "!") {
if(s.length > 1 && s[0] === "(" && s[s.length-2] === ")")
s = "fact" + s.substr(0, s.length-1);
else
s = "fact(" + s.substr(0, s.length-1) + ")";
}
var testArr = [];
testArr.push("3!");
testArr.push("2.321!");
testArr.push("(3.2+1)!");
testArr.push("(sqrt(2)+2/2^2)!");
//Have some fun with the name. Why not?
function ohIsThatAFact(str) {
if (str.slice(-1)==="!") {
str = str.replace("!","");
if(str[0]==="(" && str.slice(-1)===")")
str = "fact"+str;
else
str = "fact("+str+")";
}
return str;
}
for (var i = 0; i < testArr.length; i++) {
var testCase = ohIsThatAFact(testArr[i]);
document.write(testCase + "<br />");
}
这是按照操作要求的;使用正则表达式:
"3*(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");
你可能会得到双括号:
"(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");
我刚刚发现的我自己的答案是:
Number.prototype.fact = function(n) {return fact(this,2)}
str = str.replace(/[\d|\d.\d]+/g, function(n) {return "(" + n + ")"}).replace(/\!/g, ".fact()")
但我会看看其他答案是否会更好,认为他们是
"(sqrt(2)+2/2^2)!".replace(/(.*)!/g, "fact($1)");
(.*)!
匹配下面的正则表达式并将其匹配捕获到反向引用编号 1(.*)
.
*
!