使用jstl仅检查字符串中的数字 [英] Check string for only numbers using jstl

查看:114
本文介绍了使用jstl仅检查字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:如果给定的字符串仅包含数字,是否可以使用jstl进行检查?

My question is: is there any way to check using jstl if given a string that string contains only numbers ?

感谢.

推荐答案

您可以尝试使用c:catch将字符串隐式转换为数字并捕获任何异常(如果有).例如:

You could try to implicitly cast a string to a number and catch any exception (if there is one) using c:catch. For example:

<c:catch var="catchString">
  <c:set var="myString" value="${0 + 'asd1234'}" />
</c:catch>
<c:if test="${not empty catchString}">
  <p>Failed: ${catchString}</p>
</c:if>

<c:catch var="catchNumber">
  <c:set var="myNumber" value="${0 + '1234'}" />
</c:catch>
<c:if test="${not empty catchNumber}">
  <p>Failed: ${catchNumber}</p>
</c:if>

将输出以下内容:

<p>Failed: java.lang.NumberFormatException: For input string: "asd1234"</p>

如果要防止浮点,可以使用fmt:formatNumber进行检查以检查小数点:

If you want to prevent floats you could build a check using fmt:formatNumber to check for decimals:

<c:set var="myFloat" value="12"/>
<fmt:formatNumber value="${myFloat}" pattern="0" var="myInteger"/>
<c:if test="${myInteger - myFloat eq 0}">
  <p>No decimals</p>
</c:if>

当然,您可以将其与c:catch结合使用以捕获数字格式异常.

Of course you could combine this with the c:catch to catch number format exceptions.

<c:set var="myString" value="abc12.34"/>
<c:catch>
  <fmt:formatNumber value="${myString}" pattern="0" var="myInteger"/>
  <c:set var="passed" value="${myInteger - myString eq 0}"/>
</c:catch>

<c:if test="${passed}">
  <p>Passed</p>
</c:if>

<c:if test="${not passed}">
  <p>Failed</p>
</c:if>

这篇关于使用jstl仅检查字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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