I admittedly am not a Regular Expression expert, but would like to validate an input string and writing if/else statements for various validations just isn’t the way to do this. I’m using Java.
The input will be in the form a colon (:) separated tuple of three values. The first value will be an integer (potentially a long in terms of size/length), with the other two values being either numberic or a string.
For example, the following values would be valid:
- 1:x:456
- 2:2:3
- 3:abc:123
..and these would not:
- x:1:2
- 1::2
- 1:3::x
- 1:2
- fyz::2:1
- 1:3::3
Is there a relatively easy way to validate this input using a regular expression?
Matching
Numbers:(letters OR numbers):(letters OR numbers)If you want it such that it has to be numbers or letters only for 2nd and 3rd part, you can use this pattern:
Basically it will look for a sequence of numbers (
\\d+), followed by a twice-repeated sequence of characters::, followed by[A-Za-z], ORThe
^and$characters are anchors, meaning “beginning-of-string” and “end-of-string”Example:
Matching
Numbers:(both letters and numbers:(both letters and numbers)For this, you can use this pattern:
Which will match:
This example will match.