1,解析字符串([A-1]+[B-2]-[C-1])/2等类似字符串表达式
2.步骤一是先取出[*]中的标记id,根据id取到对应的数值,第一步解析后状态似(4+5-1)/2
3.步骤二是根据(4+5-1)/2解析成四则元算后,得到一个结果值,return string类型。
package com.zzz
{
import com.tw.controls.TextInput;
import flash.utils.Dictionary;
import mx.controls.Text;
import mx.core.UIComponent;
public class MathExpress
{
public function MathExpress()
{
}
/**
* 计算字符串中的某已单字符出现的次数
* str 被检查对象字符串
* char 出现次数的字符
* return 计算后的次数
* */
public static function MathCount(str:String,char:String):Number{
var count:int=0;
for(var i:int=0;i<str.length;i++){
if(str.charAt(i)==char){
count++;
}
}
return count;
}
/**
* 把对应[*]字符串转化成数字项
* expression 包含[]格式的带四则元算的字符串
* dic 提供替换的字典表内容
* */
public static function returnStr(expression:String,dic:Dictionary):String{
var m:int=expression.indexOf("[");
var n:int=expression.indexOf("]");
var ui:UIComponent=dic[expression.slice(m+1,n)];
var str:String=null;
if(ui is Text){
str=Text(ui).text;
}else if(ui is TextInput){
str=TextInput(ui).text;
}
return expression.replace(expression.slice(m,n+1),str);
}
/**
* 计算字符串格式的表达 如:"(12+80+79)/2"
* str 带四则运算法则的字符串对象
* return 计算后的结果
* */
public static function MathExpressByStr(str:String):String{
str = "(" + str.replace(/[^\d.+-*\/()]+/g,"") + ")";
while (/\([^()]*\)/.test(str)){
str = str.replace(/\(([^()]*)\)/g,function(s, b){
while (/[*\/]/.test(b)){
b = b.replace(/([\d.]+)([*\/])([\d.]+)/g,function(c, m, l, n){
var i:Number = parseFloat(m);
var j:Number = parseFloat(n);
return l=="*" ? i*j : i/j;
})
}
while (/[+-]/.test(b)){
b = b.replace(/([\d.]+)([+-])([\d.]+)/g,function(c, m, l, n){
var i:Number = parseFloat(m);
var j:Number = parseFloat(n);
return l=="+" ? i+j : i-j;
})
}
return b;
})
}
return str;
}
}
}以此记录。