delphi 取不规范字符串里的数值(建议使用正则)

function TForm2.getvalue(str: string): string;
var
  strTem, resultStr: string;
  len, i: Integer;
  Flag: Boolean;   //判断是否已有小数点
begin
  len := Length(Trim(str));
  if len > 0 then
  begin
    Flag := False;

    for i := 1 to len do
    begin
      strTem := Copy(str, i, 1);
      if (strTem[1] = '.') then  //小数点单独判断
      begin
        if Flag then
        begin
          resultStr := resultStr + '0';  //补0,避免出现以小数点结尾的返回值
          break
        end
        else
        begin
          Flag := True;
          resultStr := resultStr + strTem[1];
          Continue;
        end;
      end;

      if strTem[1] in ['0'..'9'] then
        resultStr := resultStr + strTem
      else
        Break;
    end;
    Result := resultStr;
  end;

end;

用法:

getvalue('1.12an')  //'1.12'
getvalue('1..2ab')  //1.0
getvalue('abc123')   //返回空值
getvalue('-123')   //返回空值,有兴趣的朋友可以再加判断重新开发


在delphi中Val是一个将字符串转换为数字的函数,
Val(S; var V; var Code: Integer)第一个参数是要转换的字符串,第二个参数存放转换后的数字,可以是整数或浮点数,第三个参数存放出错的字符索引值,例如:
Var 
  V, Code: Integer;
begin
  Val('123.445',V,Code);
end;

转换后: V = 123, Code = 4,表示字符串'123.445'转换为整数是123,在字符串第4位转换出错

iif 就是一个缩写的 If ... then ... else 语句
iif(a, b, c) a就是条件,如果为True,返回b,如果为False,返回c

 

posted @ 2022-09-15 12:00  一曲轻扬  阅读(137)  评论(0)    收藏  举报