2

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')}
Loser Coder
  • 2,338
  • 8
  • 42
  • 66

2 Answers2

2

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"

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • For some reason this is not working testStringResult = ${#strings.matches(testString, '[0-9]')} – Loser Coder Feb 01 '16 at 22:32
  • Error: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 9): Method call: Method matches(java.lang.String, java.lang.String) cannot be found on org.thymeleaf.expression.Strings type at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:273) – Loser Coder Feb 02 '16 at 06:24
  • @loser I'm not familiar with thymeleaf, but try my edited code – Bohemian Feb 03 '16 at 20:44
1

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)}
Pau
  • 14,917
  • 14
  • 67
  • 94