[英]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. 我想知道如何解析Java字符串的最后6位数字。 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, 如果出于API原因必须是正则表达式,
Pattern.compile(".{0,6}\\Z", Pattern.DOTALL)
If you need to match the last 6 codepoints (incl. supplementary codepoints), then you can replace .
如果您需要匹配最后6个代码点(包括补充代码点),则可以替换
.
with (?:[\\\?-\\\?][\\\?-\\\?]|.){0,6}
与
(?:[\\\?-\\\?][\\\?-\\\?]|.){0,6}
I'll assume that for your example for "input1" you want just "400" (not "b400"). 我假设对于您的“ input1”示例,您只需要“ 400”(而不是“ 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:
这是一个解决方案,它将返回给定字符串的最后六位数字;如果字符串不以任何数字结尾,则返回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;
}
}
As usual, store the pattern as a member to improve performance. 与往常一样,将模式存储为成员以提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.