java use Regular Expressions to generate a string

2019-07-24 12:15发布

This question already has an answer here:

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 ?

4条回答
我想做一个坏孩纸
2楼-- · 2019-07-24 12:51

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;
    }
查看更多
霸刀☆藐视天下
3楼-- · 2019-07-24 12:55

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.

查看更多
叛逆
4楼-- · 2019-07-24 13:06

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

查看更多
放荡不羁爱自由
5楼-- · 2019-07-24 13:08

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

查看更多
登录 后发表回答