Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate all possible numbers from this regular expression? [duplicate]

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<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;
}

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

How can I achieve this?

like image 932
Nikhil Avatar asked Aug 27 '15 08:08

Nikhil


People also ask

How do you repeat a pattern in regex?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.

How do you copy a regular expression?

You can use the regular Ctrl+C and Ctrl+V shortcut keys to copy and paste the selected part of the regex as is.

What does * indicate in regular expression?

Example : The Regular expression . * will tell the computer that any character can be used any number of times. Optional character – ( ? ) This symbol tells the computer that the preceding character may. or may not be present in the string to be matched.


1 Answers

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,..).

like image 125
Mazdak Avatar answered Oct 05 '22 23:10

Mazdak