문제

I have to validate following pattern in java

X.X.X

Where X can be any valid integer, but X.X.X will be in form of string.

Currently I am tokenizing the string to check for the values and also the number of levels.

Is there any better way to do this?

도움이 되었습니까?

해결책

You can use a regex for it.

The regex "[\\d]+\\.[\\d]+\\.[\\d]+" should work.

  • \\d - means a digit.
  • the '+' means one or more of the last element.
  • \\. is a dot.

Code snap:

Matcher matcher = Pattern.compile("[\\d]+\\.[\\d]+\\.[\\d]+").matcher("");
matcher.reset("11.1234.33333");
System.out.println(matcher.matches());
matcher.reset("1.abcd.3");
System.out.println(matcher.matches());

Will produce, as expected:

true
false

다른 팁

If your solution works and is understandable from you and your team, why would you change it?

You can use a regex but it is not fundamentally better. Stick to what works and is simple to you.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top