Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - RegEx for a^b instead of pow(a,b)

Here's an interesting one. Anyone have a good RegEx for converting all (first) ^ (second) to Math.pow((first), (second))?

EDIT:

The best I have so far is

s = s.replace(/((?:d+.?d*)|w+|((?:(?:[^()]*(?:([^()]*)))*)))s*^s*((?:d+.?d*)|w+|((?:(?:[^()]*(?:([^()]*)))*)))/g, 'Math.pow($1, $2)') // replace expression ^ expression with Math.pow($1, $2)

The answers so far are not general enough. They don't cover something like (var1 + var2)^2 let alone (var1 * (var2 + var3))^2

The solution will have to work with parentheses.

You can use strfriend.com to help visualize the regex as you make it. That's what I've been doing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This cannot be done with regex (at least not without lots of effort). You have to consider different layers of parenthesis, which can't be handled with a simple regular expression. I suggest to look for a library capable of parsing mathematical expression. Or you'll have to restrict the possible expression to something you can handle with a simple regex.

There is the possibility to define named and balancing capture groups in a regular expression which can be used (backreferenced) in the same regular expression. With this you would have to define the desired subset of the math syntax and both captures for the parameters. I suggest you should not reinvent the wheel and use a JS library.

http://snippets.dzone.com/posts/show/2207


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...