从字符串中提取4位数字的正则表达式 - Android

8
我需要从字符串中提取一个四位数:
例如,来自Android短信的“您的登录otp为7832。此代码将在下午12:43:09过期”。
我想提取7832或出现在字符串中的任何四位代码。 我保证字符串中只有一个四位数代码。
请帮助我。 我试图使用类似以下的模式:
str.matches(".*\\\\d+.*");

但我不太能理解正则表达式。

2个回答

21
String data = "Your otp for the login is 7832. This code will expire at 12:43:09PM";

Pattern pattern = Pattern.compile("(\\d{4})");

//   \d is for a digit 
//   {} is the number of digits here 4.

Matcher matcher = pattern.matcher(data);
String val = "";
if (matcher.find()) {        
    val = matcher.group(0);  // 4 digit number
}

谢谢您的回答。matcher.group(1)是什么意思?这里的“1”代表什么? - Gaurav Arora
有关Java正则表达式中Matcher组的疑惑,请参考以下链接:https://dev59.com/KGQn5IYBdhLWcg3w36M1 - sasikumar
如果有任何4位数字出现多次,会有问题吗?例如,当日期为21-01-2019时,可能会出现像“年份”这样的情况。 - Dhananjay M
为什么是1?我必须使用0才能使其工作。 - behelit

10

做:

\b\d{4}\b
  • \b匹配单词边界

  • \d{4}匹配4个数字

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接