簡體   English   中英

如何在Java中使用正則表達式解析字符串的最后6位數字?

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

我想知道如何解析Java字符串的最后6位數字。 所以:

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

無需正則表達式。

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

如果出於API原因必須是正則表達式,

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

如果您需要匹配最后6個代碼點(包括補充代碼點),則可以替換. (?:[\\\?-\\\?][\\\?-\\\?]|.){0,6}

我假設對於您的“ input1”示例,您只需要“ 400”(而不是“ b400”)。 這是一個解決方案,它將返回給定字符串的最后六位數字;如果字符串不以任何數字結尾,則返回null:

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

與往常一樣,將模式存儲為成員以提高性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM