简体   繁体   中英

How do I parse the last 6 digits of a string using regex in Java?

I would like to know how to parse the last 6 digits from a Java string. So:

String input1 = "b400" // the regex should return b400  
String input2 = "101010" // the regex should return 101010  
String input3 = "12345678" // the regex should return 345678  

No regex needed.

input.substring(Math.max(0, input.length() - 6));

If it has to be a regex for API reasons,

Pattern.compile(".{0,6}\\Z", Pattern.DOTALL)

If you need to match the last 6 codepoints (incl. supplementary codepoints), then you can replace . with (?:[\\\?-\\\?][\\\?-\\\?]|.){0,6}

I'll assume that for your example for "input1" you want just "400" (not "b400"). Here is a solution that will return up to the last six digits of the given string, or null if the string does not end with any digits:

public String getLastSixDigits(String source) {
  Pattern p = Pattern.compile("(\\d{0,6})$");
  Matcher m = p.matcher(source);
  if (m.find()) {
    return m.group(1);
  } else {
    return null;
  }
}

As usual, store the pattern as a member to improve performance.

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