Thursday, 17 May 2018

java - How do I generate all possible numbers from this regular expression?





I want to get a list of all possible values for a regular expression.



Input :



2W
9WW

7W0W3


where W can be any digit from 0 to 9. i.e. W = [0-9]



Output:



20,21,22,....29
900,901,...910,911,...999
70003,70013,70023,...71003,72003,...79093



What I did :



I'm using Java and decided to create an ArrayList of Integers.



I created a method ArrayList getNumbers(String regex).



ArrayList getNumbers(String regex){


ArrayList fullList = new ArrayList();

char[] cArray = regex.toCharArray(); //converted the string into a character array.

for(int i=1;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;
}


Is there any better way or library functions available to generate all such numbers?




How can I achieve this?



Any help please.


Answer



This is not quite a regex-based problem, but from an algorithmic perspective you can do the followings:




  • Count the number of W's in your string.

  • Based on the number of W's, create the product of range(0,9), for example if you have 2 W you need to create the products of two [0...9] lists that will be something like 0,0-0,1-0,2-...-9,9.


  • Loop over the combinations and replace them with a simple string formatting. For instance when you are iterating over a triple combination suppose with 3 variables i,j,k you want want to replace them in a string like 7W0W3W, you can do "7%d0%dW%d"%(i,j,k).



And if you are looking for a general regex to wrap all the cases you can use a regex like (w) (w in a capture group) then you need to first access to position of the match groups and replace them with combination items (i,j,k,..).


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...