Reputation: 121
I am trying to find the time fields between two specific words in a String. Here is few examples of my inputs
Examples
The Big Cat eats at 3:49 AM and the Big Dog eats Daily (BBB) , On 12 at 5:00 AM done
The Big Cat eats at 3:49 AM and the Big Dog eats Daily (BBB) , On 12 at 11:00 PM done
Expected Output
5:00 AM
11:00 PM
RegEx Used
(?<=Dog\s(\w+))((\d):(\d)(\d)\sAM)(?=\sdone)
I dont seem to get it properly. Not sure if the special characters in between are causing the issue. But instead of Alphanumeric, if I use Any character, then all words between my two keywords get captured. Could anyone let me know what am I doing wrong here?
Upvotes: 1
Views: 268
Reputation: 4864
You can use something like this :
String val="Big Cat eats at 3:49 AM and the Big Dog eats Daily (BBB) , On 12 at 11:00 AM done";
String REGEX="(?:Dog[a-zA-Z0-9(),])*([0-9]?[0-9]:[0-9]?[0-9] (AM|PM))(?=\\sdone)";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(val);
while(matcher.find()){
System.out.println(matcher.group());
}
Explanation:
Upvotes: 1
Reputation: 1745
How about
[0-9]?[0-9]:[0-9]?[0-9] AM|PM
Assuming your times are always in the form (x)x:(x)x AM
or (x)x:(x)x PM
For clarification:
[0-9] matches any digit from 0-9
? matches 0 or 1 occurences
x|y matches x or y
But, as others have pointed out, if the string is always the same then it is better to use substring etc. With a regex it gets much more complicated than it needs to be.
Edit: to find it between dog
and done
do
Dog.*([0-9]?[0-9]:[0-9]?[0-9] AM|PM).*done
and use \1
to get the matched time or make a substring between Dog
and done
and use the first regex.
Edit2: I added a working example:
public static void main (String[] args) {
String in = "The Big Cat eats at 3:49 AM and the Big Dog eats Daily (BBB) , On 12 at 5:00 AM done";
Pattern pattern = Pattern.compile("Dog.*([0-9]?[0-9]:[0-9]?[0-9] AM|PM).*done");
Matcher matcher = pattern.matcher(in);
System.out.println("matching");
while(matcher.find()) {
System.out.println(matcher.group(1) + "");
}
}
Output:
matching
5:00 AM
Upvotes: 2