Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top