Priyanka February 2016

Java code to generate random string based on regex

Java code to generate random string based on regex. I tried generex library , but it's not giving exact output. For example:

       Generex generex = new Generex("^[6-9]\\d{9}$");
       System.out.println(generex.random());

Output is : ^8677547981$ while i was expecting output to be 8677547981.It seems generex is not able to handle special characters like "^" , "$" etc.

Can someone pls help?

Answers


Ferrybig February 2016

Generex doesn't need ^ and $. The content created by it matches the regex fully, instead of a partial match.

Generex generex = new Generex("[6-9]\\d{9}");
System.out.println(generex.random());


Alexey Gromov February 2016

Generex uses dk.brics.automaton.RegExp class. It supports another set of regular expression operations as java.util.regex.Pattern. See RegExp API


Misteradi1 February 2016

I'm not familar with "regex" or "generex library", but I guess you could do the following:

int length = 20;        //the desired length of your string
            String s = new String("");
            for (int i = 0; i < length; i++) {
                  int rand = (int) Math.round(Math.random()*94+32);
                  s += (char) rand;
            }
            System.out.println(s);

Concerning how it works:

  • Math.random() chooses a random value between 0 and 1
  • Math.random()*94 generates a random value between 0 and 94
  • Math.random()*94 + 32 generates a random value between 32 and 126 - everything below and above are not valid character codes (see wikipedia -> ASCII)
  • the result is cast to (int) instead of long
  • s += (char) rand; --> turns the int value into a char, that is then added to a String s
  • the procedure is repeated as often as you defined with the int length, hence s.length == length

There you go - String s with length consists of random ASCII characters :)

Post Status

Asked in February 2016
Viewed 3,339 times
Voted 4
Answered 3 times

Search




Leave an answer