我想用java开发一个只匹配0-9(顺序很重要)的正则表达式
[0, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] --> match
[7, 8]
[0, 1]
[0, 1, 2, 3]
[0, 1, 2, 3]
[4, 5, 6, 7, 8, 9]
[4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] --> match
[1]
最佳答案
你想使用正则表达式来做到这一点很奇怪,所以我可以想出这个想法:
List<Integer> numbers = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
String regex = "0123456789";
String listStr = numbers.stream()
.map(number -> String.valueOf(number))
.collect(toStringJoiner(""));
if (listStr.matches(regex))
System.out.println("match");
else
System.out.println("not match");
这个想法是将您的数字列表展平为单个字符串,然后将其与 0123456789
字符串进行比较...这样您就可以使用:
if (listStr.matches(regex)) // regex approach
if (listStr.equals(regex)) // or equals approach
(not sure why you want a regex)
关于java正则表达式仅匹配0-9的列表,顺序很重要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203905/