[英]how do i find the last six digits of a string using regex in java?
How do I find the last six digits of a string using regex in java? 如何在Java中使用正则表达式查找字符串的最后六位?
For instance, I have a string: 238428342938492834823
例如,我有一个字符串: 238428342938492834823
I want to have string that finds only the last 6 digits, no matter what the length of the string is. 我想拥有一个仅能找到最后6位数字的字符串,而不管字符串的长度是多少。 I have tried "/d{6}$"
with no success. 我尝试了"/d{6}$"
,但没有成功。
Any suggestions or new ideas? 有什么建议或新想法吗?
You just used the wrong escape character. 您只是使用了错误的转义字符。 \\d{6}
matches six digits, while /d
matches a literal forward-slash followed by six literal d
's. \\d{6}
匹配六个数字,而/d
匹配一个文字正斜杠,后跟六个字母d
。
The pattern should be: 该模式应为:
\d{6}$
Of course, in Java, you also have to escape the \\
, so that: 当然,在Java中,还必须转义\\
,以便:
String pattern = "\\d{6}$";
The other answer provides you with a regex solution to this problem, however regex is not a reasonable solution to the problem. 另一个答案为您提供了此问题的正则表达式解决方案,但是正则表达式不是该问题的合理解决方案。
if (text.length >= 6) {
return text.substring(text.length - 6);
}
If you find yourself trying to use regex to solve a problem, the first thing you should do is stop and have a good think about why you think regex is a good solution. 如果您发现自己试图使用正则表达式来解决问题,那么您应该做的第一件事就是停下来,好好思考一下为什么您认为正则表达式是一个好的解决方案。
If your String always consists out of just digits, you should consider using a different datatype. 如果您的字符串始终仅由数字组成,则应考虑使用其他数据类型。
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Numberthings {
static final BigInteger NUMBER_1000000 = BigInteger.valueOf(1000000);
static final NumberFormat SIX_DIGITS = new DecimalFormat("000000");
public static void main(String[] args) {
BigInteger number = new BigInteger("238428342938492834823");
BigInteger result = number.remainder(NUMBER_1000000);
System.out.println(SIX_DIGITS.format(result.longValue()));
number = new BigInteger("238428342938492000003");
result = number.remainder(NUMBER_1000000);
System.out.println(SIX_DIGITS.format(result.longValue()));
}
}
This results in the following output: 结果为以下输出:
834823
000003
这是您如何一行完成的操作:
String last6 = str.replaceAll(".*(.{6})", "$1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.