Check if a string contains number or is numeric - Thymeleaf

一世执手 提交于 2020-01-02 11:13:17

问题


Is there a way to check if string is numeric. {#strings.isNumeric(dataField)} doesn't work.

How can I check if string contains numbers (specific number of digits as well) - is there a RegEx that can be used, or an inbuilt function that can be called?

Want to avoid this below:

{#string.contains('1') or #string.contains('2')}

回答1:


Try matches():

{#dataField.matches('[0-9]{3,8}')}

This matches a string that is from 3 to 8 digits long (inclusive). You can change those values to whatever works for you.

You can also use open-ended length ranges: [0-9]{3,} means "at least 3 digits"




回答2:


If you have in your path the library org.apache.commons.lang3 you could use it as next

${T(org.apache.commons.lang3.StringUtils).isNumeric(dataField)}

So in case you want to use an if block it would be:

<th:block th:if="${T(org.apache.commons.lang3.StringUtils).isNumeric(dataField)}">
   <p>Is numeric!</p>
</th:block/>

Otherwise, if you don't have org.apache.commons.lang3 in your classpath you could implement your own method which checks if it is numeric and then use it. So you could create a class like next:

package your.package;

public class Utils {
     public static boolean isNumeric(String data){
           //impl
           return true;
     }
}

And then use it the next expression:

${T(your.package.Utils).isNumeric(dataField)}


来源:https://stackoverflow.com/questions/35072931/check-if-a-string-contains-number-or-is-numeric-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!