patternjavaMinor
Matching a time interval using regex
Viewed 0 times
intervaltimeusingregexmatching
Problem
What I needed to do was check whether a given string matches a certain pattern. The pattern is this:
Things to keep in mind:
The 0s can be numbers from 0 to 9.
The pattern must be alone in a single line; the line has to only consist of the pattern.
I came up with this:
I tested it a few times and strings that respect the pattern return
Here's a test case:
As I'm very new to regex, I'm wondering if this is the most efficient/correct way to accomplish this.
00:00:00,000 --> 00:00:00,000Things to keep in mind:
The 0s can be numbers from 0 to 9.
The pattern must be alone in a single line; the line has to only consist of the pattern.
I came up with this:
"^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) --> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)"I tested it a few times and strings that respect the pattern return
true, the ones that don't, return false, as they should.Here's a test case:
import java.util.regex.Pattern;
public class TestCaseRegex {
public static void main(String[] args) {
//will return true
String testOne = "00:01:23,846 --> 00:01:26,212";
//will return false, there's a letter where a number should be
String testTwo = "00:01:23,84a --> 00:01:21,221";
//will return true
String testThree = "00:05:54,846 --> 00:01:16,450";
//will return false. The string doesn't match the format.
String testFour = "00:05:54,6 --> 00:0116,450";
System.out.println(patternMatch(testOne));
System.out.println(patternMatch(testTwo));
System.out.println(patternMatch(testThree));
System.out.println(patternMatch(testFour));
}
public static boolean patternMatch(String str) {
Pattern p = Pattern.compile("^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) "
+ "--> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)");
return p.matcher(str).matches();
}
}As I'm very new to regex, I'm wondering if this is the most efficient/correct way to accomplish this.
Solution
Rather than using \d, you might want to limit the matcher to valid ranges.
would match either of the timestamps and it would prevent someone from entering
\d{2}:([0-5]\d:){2},\d{3}would match either of the timestamps and it would prevent someone from entering
11:88:88,888 --> 12:99:99,999Code Snippets
\d{2}:([0-5]\d:){2},\d{3}11:88:88,888 --> 12:99:99,999Context
StackExchange Code Review Q#159077, answer score: 3
Revisions (0)
No revisions yet.