我有一个像这样的字符串:
(999.08) - (1025.67)
我需要能够找到这两个值之间的范围作为浮点,即使它们是负值,所以(-999.08) - ( - 1025.67)也在范围内。
假设我需要使用正则表达式并将两者连接成某种数组?
答案 0 :(得分:3)
通过查看其他人的答案,我无法判断他们中是否有任何一个正确处理负数。如果有人需要,我会将它扔进戒指。
function parse(str) {
// init to NaN
var result = Number.NaN;
// capture numbers in groups
var pat = new RegExp(/\((-?\d+.?\d*)\)\s*-\s*\((-?\d+.?\d*)\)/);
var match = str.match(pat);
if (match) {
// match[0] is whole match which is not useful
var a = new Number(match[1]); // 1st group is 1st number
var b = new Number(match[2]); // 2nd group is 2nd number
result = Math.abs(a - b);
}
return result;
}
答案 1 :(得分:2)
您可以使用.split将字符串拆分为“ - ”,使用replace删除括号,然后使用parseFloat这两个数字。之后,检查两个数字中的最高数字,然后减去该范围。
答案 2 :(得分:2)
有两种方法: 这是一个:很长的路要走
var myString = "(999.08) - (1025.67)"
var myFloatValues = mystring.split("-");
myFloatValues[0] = myFloatValues[0].replace("(", "").replace(")", "");
myFloatValues[1] = myFloatValues[1].replace("(", "").replace(")", "");
myFloatValues[0] = parseFloat(myFloatValues[0])
myFloatValues[1] = parseFloat(myFloatValues[1])
以下是使用正则表达式:
var myString = "(999.08) - (1025.67)"
var myFloatValues = (myString.replace(/\(*|\)*|\s*/g, "")).split("-");
myFloatValues[0] = parseFloat(myFloatValues[0])
myFloatValues[1] = parseFloat(myFloatValues[1])
注意:我一直在使用的有用网站
此网站可帮助用户生成有效的常规表达式。试试看 http://www.jslab.dk/tools.regex.php
答案 3 :(得分:2)
除了John hartsocks的回答:如果第一个值大于第二个
,设置浮点值以在值周围交换后添加一个检查function Check(myValue,myString)
{
var myFloatValues = (mystring.replace(/\(*|\)*|\s*/g, "")).split("-");
myFloatValues[0] = parseFloat(myFloatValues[0]);
myFloatValues[1] = parseFloat(myFloatValues[1]);
if (myFloatValues[0] > myFloatValues[1]) // swap
{
var temp = myFloatValues[0];
myFloatValues[0] = myFloatValues[1];
myFloatValues[1] = temp;
}
if (myFloatValues[0] < myValue && myFloatValues[1] > myValue) // this will be a problem if you dont swap them
return true;
return false;
}
答案 4 :(得分:1)
Pesuo代码:
// Our variables
float num1;
float num2;
string myString = "(999.08) - (1025.67)";
// Split the data string on - character
arrParts[] = myString.split("-");
// Loop through each resulting split
for int i = 0; i < arrParts.Count; i++)
{
// Trim result to remove whitespace
arrParts[i] = arrParts[i].trim();
// Take all the characters in string except first and last
arrParts[i] = arrParts[i].substring(1, part.length-2);
}
// Cast out numbers
num1 = (float)arrParts[0];
num2 = (float)arrParts[1];
解决方案假设
假设输入字符串格式正确,并且将提供不少于或多于2个有效浮点数。
对于范围计算:
两种方式,既可以从任一方法中减去,也可以获得绝对值来确定范围,或者采用更长的方法来保证较小的数字用于更大的
有关正则表达式的说明
我会反对在可能的情况下使用正则表达式(虽然这是非常主观的),因为它可以在将来将此代码转换为一项艰巨的任务。
如果你确实使用了正则表达式,请确保以预期的输入格式发表评论以防止这种情况发生。
答案 5 :(得分:1)