Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...