我有一条消息以短信形式进入 Android 设备,当它进入时我读到了这样的消息 您的 OTP 验证码是 5M67BX
OTP 代码
未修复。如果是这样的话,情况会有所不同,我只会使用 ([0-9]){1}([A-Z]){1}([0-9]){2}([A-Z]){1}
的 Regex
Pattern
但是,情况并不总是这样。有时全是数字。如果您可以分享 Pattern
来过滤 Java
中的代码,我们将不胜感激。谢谢
最佳答案
如果它始终是固定长度 (6) 并且始终位于字符串末尾,您可以这样做:
String s = "Your OTP verification code is 5M67BX";
String otpCode = s.substring(s.length() - 6);
编辑:这次使用正则表达式...
String s = "Your OTP verification code is 5M67BX";
String s2 = "Your updated OTP code is YW32R2 for phone verification";
Pattern p = Pattern.compile("([A-Z0-9]){6}");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group());
}
m = p.matcher(s2);
if (m.find()) {
System.out.println(m.group());
}
哪个输出...
5M67BX
YW32R2
关于java - 在Java中使用正则表达式过滤单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998575/