简体   繁体   English

Java正则表达式查找号

[英]Java regular expression finding number

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'. 即使我只是尝试'^ \\ d \\ d',此代码也不会打印任何内容。

if I'm correct '^' stands for line beginning '\\d' for any digit 如果我是正确的,则'^'代表以'\\ d'开头的任意数字行

I also tried to replace '^' with '\\A' If i change pattern to 我还尝试将'^'替换为'\\ A'如果我将模式更改为

pat = Pattern.compile("\\d\\d");

it returns position at 6. Can somebody tell me why the first code is not working?:) 它返回位置6。有人可以告诉我为什么第一个代码不起作用吗?

THX 谢谢

You need to print the group index 0 inside the if block, so that it would print the matched characters. 您需要在if块中打印组索引0,以便它将打印匹配的字符。

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. 在我的计算机上,您的示例Test.main运行良好,可能取决于JVM的实现。 I think if you open then you also need to close regex with question mark: 我认为,如果您打开,那么还需要用问号关闭正则表达式:

"^\\d\\d?"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM