本文介绍了Apache Commons Text:特殊字符的随机字符串java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 apache commons-text:RandomStringGenerator 来生成一个随机的 String,如下所示:

I'm using apache commons-text:RandomStringGenerator for generating a random String like so:

//Utilities
private static RandomStringGenerator generator(int minimumCodePoint, int maximumCodePoint, CharacterPredicates... predicates) {
    return new RandomStringGenerator.Builder()
            .withinRange(minimumCodePoint, maximumCodePoint)
            .filteredBy(predicates)
            .build();
}

public static String randStringAlpha(int length) {
    return generator('A', 'z', CharacterPredicates.LETTERS).generate(length);
}

public static String randStringAlphaNum(int length) {
    return generator('1', 'z', CharacterPredicates.LETTERS, CharacterPredicates.DIGITS).generate(length);
}

//Generation
private void foo() {
    String alpha = randStringAlpha(255);
    String num = randStringAlphaNum(255);
}

我正在寻找一种使用相同库生成以下内容的方法:

  • A - 特殊字符(可能仅限于键盘特殊字符)
  • B - alpha + A
  • C - 数字 + A
  • D - alpha + num + A

    I'm looking for a way to use the same library to generate to following:

  • A - special characters (could be limited to keyboard special characters)
  • B - alpha + A
  • C - num + A
  • D - alpha + num + A

    我已经检查了 CharacterPredicates enum 但它只有 LETTERSDIGITS 用于过滤.任何帮助将不胜感激!

    I already checked the CharacterPredicates enum but it only has LETTERS and DIGITS for filtering. Any help would be really appreciated!

    我决定搁置我当前的解决方案以支持

    I decided to shelf my current solution in favor of this answer.
    To clarify the scope of 'special characters' I was actually looking for this subset:

    案例 A 的片段:

    public static CharSequence asciiSpecial() {
        return asciiCharacters().toString().replaceAll("(\\d|[A-z])","");
    }
    

    推荐答案

    您的特殊字符"类别非常模糊.只要保持在 ASCII 范围内,所有字符都是字母、数字或特殊",但可以用普通键盘输入.换句话说,您根本不需要为此指定过滤器.另一方面,当您离开 ASCII 范围时,您必须关注多种字符类别(例如,您不想在任意点插入随机组合字符),此外,没有一般测试是否可以用键盘输入字符(因为没有通用键盘)...

    Your category "special characters" is quiet fuzzy. As long as you stay with the ASCII range, all characters are either letter, digit or "special", but can be entered with an ordinary keyboard. In other words, you don’t need to specify a filter at all for that. On the other hand, when you leave the ASCII range, there is a variety of character categories you would have to care of (e.g. you don’t want to insert random combining characters at arbitrary points), further, there is no general test whether a character can be entered with a keyboard (as there is no general keyboard)…

    但请注意,您尝试使用该库的代码已经比执行实际工作的代码大.例如.要获得随机字母字符串,您可以使用

    But note that your code trying to use that library is already bigger than code doing the actual work would be. E.g. to get a random letter string, you could use

    public static String randStringAlpha(int size) {
        return ThreadLocalRandom.current().ints('A', 'z'+1)
            .filter(Character::isLetter)
            .limit(size)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
    }
    

    或者可能更有效的变体

    public static String randStringAlpha(int size) {
        return ThreadLocalRandom.current().ints(size, 'A', 'Z'+1)
            .map(c -> ThreadLocalRandom.current().nextBoolean()? c: Character.toLowerCase(c))
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
    }
    

    没有任何第三方库.

    同样,您可以使用

    public static String randomString(int size, CharSequence validChars) {
        return ThreadLocalRandom.current().ints(size, 0, validChars.length())
            .map(validChars::charAt)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
    }
    public static String randomString(int minSizeIncl, int maxSizeIncl, CharSequence valid) {
        return randomString(
            ThreadLocalRandom.current().nextInt(minSizeIncl, maxSizeIncl), valid);
    }
    public static CharSequence asciiLetters() {
        return IntStream.concat(IntStream.rangeClosed('A','Z'), IntStream.rangeClosed('a','z'))
            .collect(StringBuilder::new,StringBuilder::appendCodePoint,StringBuilder::append);
    }
    public static CharSequence asciiLetterOrDigit() {
        return IntStream.concat(asciiLetters().chars(),IntStream.rangeClosed('0', '9'))
            .collect(StringBuilder::new,StringBuilder::appendCodePoint,StringBuilder::append);
    }
    public static CharSequence asciiCharacters() {
        return IntStream.rangeClosed('!', '~')
            .collect(StringBuilder::new,StringBuilder::appendCodePoint,StringBuilder::append);
    }
    

    你可以通过结合两种方法来使用,例如
    RandomString.randomString(10, asciiLetters()),
    RandomString.randomString(10, asciiLetterOrDigit()),或
    RandomString.randomString(10, asciiCharacters()), resp.它们的可变大小对应物,如 RandomString.randomString(10, 20, asciiCharacters()).

    Which you can use by combining two methods, e.g.
    RandomString.randomString(10, asciiLetters()),
    RandomString.randomString(10, asciiLetterOrDigit()), or
    RandomString.randomString(10, asciiCharacters()), resp. their variable-size counterparts like RandomString.randomString(10, 20, asciiCharacters()).

    CharSequence 可以在多个字符串生成调用之间重复使用,类似于构建一个 RandomStringGenerator 并多次使用它.

    The CharSequences can be reused between multiple string generation calls, would be similar to building a RandomStringGenerator and using it multiple times.

    这篇关于Apache Commons Text:特殊字符的随机字符串java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-16 10:17