0

如何在 Java 中为长数据类型构建正则表达式,我目前有一个用于 3 个双精度值的正则表达式作为我的模式:

String pattern = "(max=[0-9]+\\.?[0-9]*) *(total=[0-9]+\\.?[0-9]*) *(free=[0-9]+\\.?[0-9]*)";

我正在使用以下行构建模式:

Pattern a = Pattern.compile("control.avgo:", Pattern.CASE_INSENSITIVE);

我想从文件中匹配下面示例文本中等号后面的数字control.avgo

max=259522560, total=39325696, free=17979640

我需要做什么来更正我的代码以匹配它们?

4

3 回答 3

3

会不会是你真正需要的

Pattern a = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);

代替

Pattern a = Pattern.compile("control.avgo:", Pattern.CASE_INSENSITIVE);

因为您当前的代码"control.avgo:"用作正则表达式,而不是pattern您定义的。

于 2013-06-27T16:07:03.207 回答
2

您需要解决几个错误,包括:

  • 您的模式指定实数,但您的问题要求长整数。
  • 您的模式省略了正在搜索的字符串中的逗号。
  • Pattern.compile() 的第一个参数是正则表达式,而不是正在搜索的字符串。

这将起作用:

    String sPattern = "max=([0-9]+), total=([0-9]+), free=([0-9]+)";
    Pattern pattern = Pattern.compile( sPattern, Pattern.CASE_INSENSITIVE );

    String source = "control.avgo: max=259522560, total=39325696, free=17979640";
    Matcher matcher = pattern.matcher( source );
    if ( matcher.find()) {
        System.out.println("max=" + matcher.group(1));
        System.out.println("total=" + matcher.group(2));
        System.out.println("free=" + matcher.group(3));
    }

如果要将找到的数字转换为数字类型,请使用Long.valueOf( String ).

于 2013-06-27T16:13:25.293 回答
2

如果您只需要找到任何以“=”开头的数字...

String test = "3.control.avgo: max=259522560, total=39325696, free=17979640";
// looks for the "=" sign preceding any numerical sequence of any length
Pattern pattern = Pattern.compile("(?<=\\=)\\d+");
Matcher matcher = pattern.matcher(test);
// keeps on searching until cannot find anymore
while (matcher.find()) {
    // prints out whatever found
    System.out.println(matcher.group());
}

输出:

259522560
39325696
17979640
于 2013-06-27T16:15:52.967 回答