我想要一个正则表达式的所有可能值的列表。
输入:
2W
9WW
7W0W3其中W可以是从0到9的任意数字。
输出:
20,21,22,....29
900,901,...910,911,...999
70003,70013,70023,...71003,72003,...79093我所做的:
我使用Java并决定创建一个整数的ArrayList。
我创建了一个方法ArrayList<Integer> getNumbers(String regex)**.**
ArrayList<Integer> getNumbers(String regex){
ArrayList<Integer> fullList = new ArrayList<Integer>();
char[] cArray = regex.toCharArray(); //converted the string into a character array.
for(int i=1;i<cArray.length;i++) {
if(cArray[i] == 'W') {
for(int j=0;j<10;j++) {
//I'm not sure what goes here
fullList.add(the number with 'w' at this index replaced by 'j');
}
}
}
return fullList;
}是否有更好的方法或库函数来生成所有这样的数字?
我怎样才能做到这一点?
发布于 2015-08-27 08:33:15
最好将输入字符串称为“模式”,而不是“正则表达式”。另外,最好是创建一个“虚拟”列表,根据需要生成字符串。下面是示例实现:
public static List<String> getNumbers(String pattern) {
final char[] chars = pattern.toCharArray();
int size = 1;
for(char ch : chars)
if(ch == 'W') {
if(size == 1_000_000_000)
throw new IllegalArgumentException("Too many 'W' to fit the list");
size*=10;
}
final int finalSize = size;
return new AbstractList<String>() {
@Override
public String get(int index) {
char[] res = chars.clone();
for(int i=res.length-1; i>=0; i--) {
if(res[i] == 'W') {
res[i] = (char) ('0'+(index % 10));
index/=10;
}
}
return new String(res);
}
@Override
public int size() {
return finalSize;
}
};
}首先,我们计算'W'字符的数量,并相应地计算目标列表大小。然后,我们返回一个AbstractList的实现,对于给定的列表索引,用'W'符号替换为10的剩余的索引除法。此列表不占用内存,它只在请求时生成String。如果你想得到这样的名单的硬拷贝,你可以使用new ArrayList<>(getNumbers(pattern)).
https://stackoverflow.com/questions/32243814
复制相似问题