如何在句子中为给定的多个数字编写正则表达式?

时间:2017-06-17 16:54:58

标签: java regex

如果我的2位数字(可以是任何东西)在一个没有被空格分隔的数字中找到,我必须返回true或false

这里2个数字(1和3)以两个不同的数字(8913011,12)存在,它返回true。这是错误的情况

String styy = "12 46499 8913011";
//             ^           ^
boolean contains = styy.matches("(.*\\b[0-9]*?(1[0-9]*?3|3[0-9]*?1)[0-9]*?\\b.*?)");
System.out.println(contains);

我想搜索这两个数字(1和3)两个数字,如4153

String styy = "4153 245 345"
//              ^ ^

在上面的字符串中,2个数字出现在一个数字中。

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,那么你可以在没有正则表达式的情况下解决它:

首先,你必须逐个检查你的数字,为此你可以用空格分割输入 其次,你可以逐个检查这个数字,如果其中一个可以包含你的degits 1和3然后它是正确的输入,否则它不是,这里是你可以使用它的一段代码:

String styy = "4153 245 345";
String[] splt = styy.split(" ");
boolean correct = false;
for (String number : splt) {
    if (number.contains("1") && number.contains("3")) {
        correct = true;
        break;
    }
}
System.out.println(correct ? "Correct number" : "Not correct number");

答案 1 :(得分:0)

一组数字中的3和1

在你的代码中,如果传入的字符串中的任何数字包含数字1和3,则该值应返回

boolean contains = styy.matches("\\d*1(\\d*)3\\d*|\\d*3(\\d*)1\\d*");

Short Description:
  any digits before a 1, any digits between a 3 and any digits after it
OR
  any digits before a 3, any digits between a 1 and any digits after it

答案 2 :(得分:0)

如何使用2个正向前瞻?

boolean contains = styy.matches(".*\\b(?=\\d*1)(?=\\d*3)(\\d+).*");