简体   繁体   中英

regular expression :inserting * make it computable

I have a regular expression as

ysin(yx)

i need to insert * as y*sin(y*x)

suppose my equation is yxsin(y) i need to get output as y*x*sin(y) i tried with this code

function addStars(str) {
    return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 });
}
var t=addStars("ysin(yx)");
alert(t);

what is wrong with this code.

I suggest using regular back-references in this case since you are not analyzing or manipulating the capture groups. The problem is that you are trying to match some letter after a ) with /(\\))([A-Za-z])/g - and you do not have any text after ) in your example string ysin(yx) .

Here is a possible fix where I combined the x and y into a character class and set a capture group to be able to restore them in the result:

 function addStars(str) { return str.replace(/([xy])([A-Za-xz])/g,"$1*$2"); // | | ^ // ----------------------| } var t=addStars("ysin(yx)"); document.write(t + "<br/>"); var t=addStars("yxsin(y)"); document.write(t);

I've generalized the approch using a function list as an anchor and splitting the variables list. The regex is case insensitive and accepts any letter [az] as variables prior and as arguments of the function. The trigonometric function list is (asin|acos|atan|sin|cos|tan) (can be expanded as well, only remember to put the longest function names first!).

Check if can be useful:

 function addStars(str) { return str.replace(/([az]*?)(asin|acos|atan|sin|cos|tan)\\(([^\\)]*)\\)/i, function(str, vars, funcName, args) { return vars.split('').join('*') + '*' + funcName + '(' + args.split('').join('*')+')';}); } var t=addStars("ysin(yx)"); document.write(t + "<br/>"); var t=addStars("yxsin(y)"); document.write(t + "<br/>"); var t=addStars("ycos(abyxz)"); document.write(t + "<br/>"); var t=addStars("yxatan(yxz)"); document.write(t + "<br/>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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