[英]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.