Reputation: 1031
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:
..and these would not:
Is there a relatively easy way to validate this input using a regular expression?
Upvotes: 1
Views: 5267
Reputation: 12486
If your strings may contain colons inside quoted strings, like this:
1234:"Ratio is 1:20":"Fuel:Oil"
Then you need to work around the colons inside the string. Building on Barton Chittenden's answer, you could use this:
^(\d+):(".+?"|[^"][^:]*):(".+?"|[^"][^:]*)$
See it on regexr. It breaks down for silly things like 123:":"
, but you could modify the regex to handle these edge cases too.
Upvotes: 0
Reputation: 80001
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:
String pattern = "^\\d+(:([A-Za-z]+|\\d+)){2}$";
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:
public class RegexTest {
public static void Main(String[] args) {
String pattern = "^\\d+(:([A-Za-z]+|\\d+)){2}$";
String example = "333:abc:123456";
if (example.matches(pattern)) {
System.out.println("Matches");
}
}
}
Numbers:(both letters and numbers:(both letters and numbers)
For this, you can use this pattern:
String pattern = "^\\d+(:[A-Za-z0-9]+){2}$";
Which will match:
public class RegexTest {
public static void Main(String[] args) {
String pattern = "^\\d+(:[A-Za-z0-9]+){2}$";
String example = "333:a3b4c:12adf3456";
if (example.matches(pattern)) {
System.out.println("Matches");
}
}
}
This example will match.
Upvotes: 1
Reputation: 4418
I would suggest the following:
^[0-9]+:[^:]+:[^:]+
Start of line, followed by digits, followed by colon followed by any number of non-colon characters, followed by a colon followed by non-colon characters.
This should be the most flexible colon delimited format that starts with digits.
Upvotes: 1
Reputation: 3709
/\d+:\[a-zA-Z0-9]+:\[a-zA-Z0-9]+/
if you knew the max lengths you could do
/\d{1,X}:[a-zA-Z0-9]{1,Y}:[a-zA-Z0-9]{1,Z}/
Upvotes: 0
Reputation: 34621
For the case where the 2nd and 3rd values can be mixed:
/^[0-9]+:[0-9a-zA-Z]+:[0-9a-zA-Z]+$/
For the case where they can be only a string or only a number:
/^[0-9]+:([0-9]+)|([a-zA-Z]+):([0-9]+)|([a-zA-Z]+)$/
Upvotes: 1