测试字符串是否可以在FreeMarker中转换为数字 [英] test if string can be converted to a number in FreeMarker

查看:85
本文介绍了测试字符串是否可以在FreeMarker中转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试是否可以在FreeMarker中将字符串转换为数字.例如,可以转换"123"和"3.14",但不能转换"foo".我知道我可以通过在字符串上使用数字方法(例如"123"?number )并查看它是否产生错误来对此进行测试,但是我正在寻找一种方法来对此进行测试不会导致错误.

I am trying to test whether a string can be converted into a number in FreeMarker. For example, "123" and "3.14" can be converted, but "foo" can't. I know that I can test for this by using the number method on the string (e.g. "123"?number) and seeing whether it produces an error, but I am looking for a way to test for this without causing an error.

我尝试了?matches("^ \ d + $"),它对于整数很有效,但是我正在寻找对所有数字都适用的东西.

I tried ?matches("^\d+$"), and it works fine for integers, but I am looking for something that works on all numbers.

我可能可以使用更复杂的正则表达式来做到这一点,但我想知道是否有更简单的方法.

I can probably do it using a more sophisticated regex, but I am wondering if there is a simpler way.

推荐答案

更简单的方法是在FreeMarker中不要这样做:-)听起来像控制器(或模型上的方法)应该在做些事情,而不是在查看模板.也就是说,您有几种选择:

The simpler way is to not do it in FreeMarker :-) This sounds like something controller (or method on model) should be doing rather than view template. That said, you have a few options:

  1. 使用<#attempt>中内置的?number/<#recover> 块.
  2. 在您的一个模型对象中编写一个方法,以检查您的字符串是否为数字并从模板中调用它.
  3. 编写一个自定义指令为您执行此操作.

这篇关于测试字符串是否可以在FreeMarker中转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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