Reputation: 181
I'm trying to parse log using regex. Unfortunately I' stacked on following string. Trying to find line beginning with time
for example:
String p="11:33:00.0 2000 0.0 ....... # 0.0 ....... # 0.0 ....... # 0.0 ...";
I have following code:
public class Test {
public static void main(String[] args) {
String p="11:33:00.0 2000 0.0 ....... # 0.0 ....... # 0.0 ....... # 0.0 ...";
Pattern pat = Pattern.compile("^\\d\\d\\:\\d\\d*");
Matcher m = pat.matcher(p);
if (m.find()) {
System.out.println(m.start());
System.out.println(p.substring(m.start()));
}
}
}
this code prints nothing even if I tried just '^\d\d'.
if I'm correct '^' stands for line beginning '\d' for any digit
I also tried to replace '^' with '\A' If i change pattern to
pat = Pattern.compile("\\d\\d");
it returns position at 6. Can somebody tell me why the first code is not working?:)
THX
Upvotes: 0
Views: 63
Reputation: 992
On my computer your example Test.main worked fine, maybe it's dependant on JVM implementation. I think if you open then you also need to close regex with question mark:
"^\\d\\d?"
Upvotes: 0
Reputation: 174696
You need to print the group index 0 inside the if block, so that it would print the matched characters.
String p="11:33:00.0 2000 0.0 ....... # 0.0 ....... # 0.0 ....... # 0.0 ...";
Pattern pat = Pattern.compile("^\\d\\d\\:\\d\\d*");
Matcher m = pat.matcher(p);
if (m.find()) {
System.out.println(m.group(0));
}
Output:
11:33
Upvotes: 1