0

Hi I'm trying to setup a hostname pattern for a minecraft-server plugin. It will look through the arguments of the chat message and try to find any possible hostnames. The code works unless the message only contains one word.

Here's the class that checks the message event:

package com.carlgo11.preventip.player;

import com.carlgo11.preventip.Main;
import java.util.regex.Matcher;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

public class ChatEvent implements Listener {

Main plugin;

public ChatEvent(Main plug)
{
    super();
    this.plugin = plug;
}

@EventHandler
public void PlayerChat(AsyncPlayerChatEvent e)
{
    if (!plugin.getConfig().getBoolean("ignore-chat")) {
        Player p = e.getPlayer();
        String msg = e.getMessage();
        String[] args = msg.split(" ");
        Boolean match = false;
        if (!p.hasPermission("preventip.ignore")) {
            for (int i = 0; i < args.length; i++) {
                Matcher hnre = plugin.hostnamePattern.matcher(msg.toString());
                Boolean hnrematch = hnre.find();
                if (hnrematch) {
                        match = true;
                        break;
                }
            }
            if (match) {
                e.setCancelled(true);
                Action.action(p, plugin);
            }
        }
    }
}
}

And here's the pattern

Pattern hostnamePattern = Pattern.compile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$");

So when args contains more than 1 word the pattern works but if not the pattern acts as true even though hnre.find() outputs false.

Thanks in advance :)

fabian
  • 80,457
  • 12
  • 86
  • 114
Carlgo11
  • 1
  • 1

1 Answers1

0

First at all, please use Java Naming Conventions (see https://stackoverflow.com/tags/java/info).

About your method design there is something that I find a little strange, first you split the message:

String[] args = msg.split(" ");

but then you try to match your regex with the whole message, for each word in your message:

Matcher hnre = plugin.hostnamePattern.matcher(msg.toString());

I think you can simplify all doing something like:

//remove ^ and $ to find the pattern in any position in your message. I assume the correctness of the pattern
Pattern hostnamePattern = Pattern.compile("(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])");

//Let msg a annoying message
String msg = "ereh un enfermo, ereh un enfermo, ereh un enfermo de ciberseso me pone loh cuenno " +
            "me pone lo cuenno www.tiahbuena.com esto vida mia eh un infienno";
Matcher m = hostnamePattern.matcher(msg);
boolean hnrematch = m.find();
if(hnrematch){
    //cancel what you want
}

Hope it helps

Community
  • 1
  • 1
eltabo
  • 3,749
  • 1
  • 21
  • 33