1
private static final Pattern namePattern = 
    Pattern.compile("[a-zA-Z0-9_-]{3,12}");

if (player.getName().length() < 3 || 
        player.getName().length() > 12 || 
        namePattern.matcher(player.getName()).matches()) {
    player.ban("[Autoban] Character-name PE", true);
    return;
}

The code is kinda obvious, I hope

If the players name is longer than 12 or shorter then 3, or have any symbols that shouldnt be i a name = BAM, ban!

but even thought my player name is like Chaos or test, it gets autobanned by this code. idk if the namepattern Pattern blocks characters aswell, I just it to block symbols like "!#&%¤/&%(/)(/(=)$@£$@£{€@£ yeh... What am I doing wrong :(?

1 Answer 1

3

I think you meant (!namePattern.matcher(player.getName()).matches()).

Also, you could've use only the regex match: [a-zA-Z0-9_-]{3,12} since it checks for length.

Edit:

You can use such a function

public void banIfNeeded(Player player)
{
    Pattern namePattern = Pattern.compile("[a-zA-Z0-9_-]{3,12}");
    if(!namePattern.matcher(player.getName()).matches()) {
        System.out.print("Banned"); 
        // Ban somehow
    }
}

As @bkail commented (thanks!), there's no need for the ^ and \z so I removed them :)

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks it works now but even if my char is named something with !"__#!"_#! or a symbol like that, it doesnt get banned. only lenght check seems to work.
Anchors ("^" and "\z") are unnecessary when using .matches().
How can I check if the player use a symbool in the name then? i want to block all symbols
How can I check if the player use a symbool in the name then? i want to block all symbols
I just gave you an example. just use player.getName() instead of s.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.