我只是在练习一些编码问题,我得到了像这样的问题定义
Given an array of numbers, the task is to print only those numbers which have only 1, 2 and 3 as their digits.
为此我编写了这样的代码
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
请帮助我改进我的正则表达式
最佳答案
你可以直接替换:
.filter(data -> !String.valueOf(data).matches("(0|[a-zA-Z4-9].*)"))
与
.filter(data -> String.valueOf(data).matches("[123]+"))
我进行了两项更改,删除了非运算符 !
并使用了此正则表达式 [123]+
,它匹配类 [123]< 中的一个或多个数字
输出
3
22
123
关于java - 程序排除除 1,2,3 之外的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48138434/