RegEx for a ^ b而不是pow(a,b) [英] RegEx for a^b instead of pow(a,b)

查看:61
本文介绍了RegEx for a ^ b而不是pow(a,b)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有趣的。任何人都有一个很好的RegEx将所有(第一个)^(第二个)转换为Math.pow((第一个),(第二个))?

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

编辑:

我到目前为止最好的是

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



<到目前为止,答案还不够全面。它们不包括像(var1 + var2)^ 2更不用说(var1 *(var2 + var3))^ 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.

您可以使用strfriend.com来帮助您在制作时正确显示正则表达式。这就是我一直在做的事情。

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

推荐答案

这不能用正则表达式完成(至少不需要付出很多努力)。您必须考虑括号的不同层,无法使用简单的正则表达式处理。我建议寻找一个能够解析数学表达式的库。或者你必须将可能的表达式限制为你可以用一个简单的正则表达式处理的东西。

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.

有可能在正则表达式中定义命名和平衡捕获组可以在同一个正则表达式中使用(反向引用)。有了这个,你必须定义数学语法的所需子集和两个参数的捕获。我建议你不要重新发明轮子并使用JS库。

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

这篇关于RegEx for a ^ b而不是pow(a,b)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆