简体   繁体   中英

How do I build a regex to match these `long` values?

How do I build a regular expression for a long data type in Java, I currently have a regex expression for 3 double values as my pattern:

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

I am constructing the pattern using the line:

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

I want to match the numbers following the equals signs in the example text below, from the file control.avgo .

max=259522560, total=39325696, free=17979640

What do I need to do to correct my code to match them?

Could it be that you actually need

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

instead of

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

because your current code uses "control.avgo:" as the regex, and not the pattern you have defined.

You need to address several errors, including:

  • Your pattern specifies real numbers, but your question asks for long integers.
  • Your pattern omits the commas in the string being searched.
  • The first argument to Pattern.compile() is the regular expression, not the string being searched.

This will work:

    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));
    }

If you want to convert the numbers you find to a numeric type, use Long.valueOf( String ) .

In case you only need to find any numerical preceded by "="...

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());
}

Output:

259522560
39325696
17979640

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.

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