1.12.2 Check if string has only english characters

Discussion in 'Spigot Plugin Development' started by TaskID, Aug 17, 2020.

  1. I want to disallow users from using any special characters in their name. They should be able to use the whole english keyboard, so
    Code (Java):
    a-z, 0-9, [], (), &, ", %, $, ^, °, #, *, +, ~, §, ., ,, -, ', =, }{
    and so on. So they should be allowed to use every "normal" english character which you can type with your keyboard.

    How can I check that?
  2. I suggest just using a regex checking for any characters except the allowed ones. If it matches, you have at least one illegal character in there.
  3. Yes, but what regex do I have to use? I've never really worked with that.
  4. Have a look at regex101. It has all the explanation you need, and since this falls into the "learn java" category somewhat asking here is not the correct place :)
  5. Well I've heard that Regex is performance consuming. Maybe try benchmarking Regex and a big if statement for every char.

    For a-z and A-Z you can check them as integer:

    Code (Java):
    if((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char == '#' ... )
      // do something
      // do something else
    • Useful Useful x 1
  6. In your case, there is no need for a regex. Just loop through every character and see if their values are ASCII (resp. only a sub-set of ASCII if you don't want to include all of the special 0-31 chars). In other words:
    Code (Java):
    boolean isEnglishOnly = true;
    for (char c: chars.toCharArray()) {
        if (c < ' ' || c > '~') {
            isEnglishOnly = false;
    this would print true, for "Hello, World!" but false for "Hello, Wörld!". Have a look at an Ascii-table for details
    • Agree Agree x 2
    • Winner Winner x 1