java use Regular Expressions to generate a string

2019-07-24 12:34发布

问题:

This question already has an answer here:

  • Using Regex to generate Strings rather than match them 11 answers

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 ?

回答1:

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.



回答2:

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



回答3:

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



回答4:

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