【问题标题】:program to exclude number having apart from 1,2,3排除除 1,2,3 之外的数字的程序
【发布时间】:2018-06-16 17:33:41
【问题描述】:

我只是在练习一些编码问题,我得到了类似的问题定义

给定一个数字数组,任务是只打印那些只有 1、2 和 3 作为数字的数字。

为此我编写了这样的代码

public class PrintArrays {

    public static void main(String[] args) {
        PrintArrays p = new PrintArrays();
        List<Integer> list =    p.findNumbers(new int[]{22,123,456,145,5,3,000,10,453});
        String s = new String("23");
        list.forEach(data -> System.out.println(data));
    }

    private List<Integer> findNumbers(int[] is) {
        List<Integer> list = new ArrayList<>();
        Arrays.stream(is)
                .filter(data -> !String.valueOf(data)
                .matches("(0|[a-zA-Z4-9].*)"))//tried to match if it contains  alphabets or any other number apart from 1,2,3
                .sorted()
                .forEach(data -> list
                .add(data));
        return list;
    }
}

我的愿望输出是

3
22
123

我得到了什么:

3
10
22
123
145

请帮助我改进我的正则表达式

【问题讨论】:

  • 你为什么是否定匹配?在此处创建正则表达式要容易得多。
  • 我首先做了我想到的,你的方法很容易

标签: java regex lambda regex-group


【解决方案1】:

您不需要使用正则表达式来完成任务 - 一个简单的循环枚举 int 的数字就足够了:

static boolean is123(int x) {
    if (x == 0) {    // Treat zero as a special case
        return false;
    }
    while (x != 0) { // Divide by ten until we get to zero
        if (x%10 < 1 || x%10 > 3) {
            // If we get a digit other than 1, 2, or 3, return false
            return false;
        }
        x /= 10;
    }
    return true;
}

下面是如何使用它来过滤数字:

List<Integer> result = Arrays.stream(is)
    .filter(Test::is123) // Test is the name of the class enclosing is123 method
    .sorted()
    .boxed()
    .collect(Collectors.toList());

Demo.

【讨论】:

    【解决方案2】:

    你可以替换:

    .filter(data -> !String.valueOf(data).matches("(0|[a-zA-Z4-9].*)"))
    

    .filter(data -> String.valueOf(data).matches("[123]+"))
    

    我做了两个更改删除了 not 运算符 ! 并使用了这个正则表达式 [123]+ 匹配类 [123] 中的一个或多个数字

    输出

    3
    22
    123
    

    【讨论】:

    • 是的。但是你能帮我改进我给的正则表达式吗?只是想知道我的问题
    • @LowCool 问题是,你的正则表达式应该匹配什么?
    • @LowCool 很难说正则表达式试图做什么。它匹配以0 开头的任何内容或[a-zA-Z4-9] 中的任何内容,后跟任意数量的任意字符。
    • 我只是想通过分组尝试,所以我添加了喜欢它是否包含 0 或其他部分
    • 我真的不明白你@LowCool 你能编辑你的问题并描述你的问题吗!
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多