2

i want to generate random String who have this form

[A-Za-z0-9]{5,10}

I don't have any idea how to do it, i should use regular expressions or random function ?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user2328999
  • 91
  • 3
  • 12
  • Maybe [this](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) will be of help to you – Menno May 01 '13 at 11:16

4 Answers4

2

I'd stick to a Java-solution in this case, something along the lines of:

private String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGRHIJKLMNOPQRSTUVWXYZ0123456789";

public String getRandomValue(int min, int max) {
    Random random = new Random();
    int length = random.nextInt(max - min + 1) + min;
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        sb.append(allowedChars.charAt(random.nextInt(allowedChars.length())));
    }
    return sb.toString();
}

You can call this with getRandomValue(5, 10);

I have not tried this code, since I have no IDE available

Note, if you're not apposed to using third party libraries, there are numerous available.

Menno
  • 12,175
  • 14
  • 56
  • 88
1

You can't use regexes (in Java) to generate things.

You need to use a "random" number generator (e.g. the Random class) to generate a random number (between 5 and 10) of random characters (in the set specified.) In fact, Java provides more than one generator ... depending on how important randomness is. (The Random class uses a simple pseudo-random number generator algorithm, and the numbers it produces are rather predictable ...)

I suspect this is a "learning exercise" so I won't provide code. (And if it is not a learning exercise, you should be capable of writing it yourself anyway ...)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You could use RandomStringUtils.randomAlphanumeric(int count) found in Apache's commons-lang library and specify a different count argument each time (from 5 to 10)

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html#randomAlphanumeric%28int%29

0

Its not possible to generate random String using regular expression. Regular expression is way to specify and recognize Patterns of texts, characters and words. You can use following code to generate random string.

 public static String createRandomString(int length)
    {
        String randomString = "";
        String lookup[] = null;
        int upperBound = 0;
        Random random = new Random();

        lookup = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        upperBound = 36;

        for (int i = 0; i < length; i++)
        {
            randomString = randomString + lookup[random.nextInt(upperBound)];
        }

        return randomString;
    }
Alpesh Gediya
  • 3,706
  • 1
  • 25
  • 38