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
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
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?"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.