You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何提取指定文本后的OTP验证码数字?

提取指定前缀后的OTP数字

可以通过两种方式精准提取目标OTP,避免捕获无关数字:

方法一:使用正则正向预查

利用正则的正向零宽断言,定位到指定前缀后的连续数字序列,只匹配前缀之后的第一组连续数字:

String str = "Your OTP for Darshann is : 9999%n 12341234123";
// 正则表达式:匹配"Your OTP for Darshann is : "之后的连续数字
Pattern otpPattern = Pattern.compile("(?<=Your OTP for Darshann is : )\\d+");
Matcher matcher = otpPattern.matcher(str);

if (matcher.find()) {
    String otp = matcher.group();
    System.out.println(otp); // 输出结果:9999
}

方法二:分步截取+提取

先截取前缀之后的子串,再从子串中提取第一组连续数字,逻辑更直观:

String str = "Your OTP for Darshann is : 9999%n 12341234123";
String otpPrefix = "Your OTP for Darshann is : ";

// 定位前缀结束的位置
int prefixEndIndex = str.indexOf(otpPrefix) + otpPrefix.length();
// 获取前缀之后的子串
String contentAfterPrefix = str.substring(prefixEndIndex);

// 提取子串中的第一组连续数字
Pattern numPattern = Pattern.compile("\\d+");
Matcher numMatcher = numPattern.matcher(contentAfterPrefix);

if (numMatcher.find()) {
    String otp = numMatcher.group();
    System.out.println(otp); // 输出结果:9999
}

说明

  • 两种方法都只会捕获前缀后的第一组连续数字(即9999),不会包含后续的12341234123。
  • 如果OTP长度固定(比如4位),也可以把正则中的\\d+改为\\d{4},进一步缩小匹配范围。

内容的提问来源于stack exchange,提问作者MARSH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:01:44