简体   繁体   中英

Java - How to parse this String using RegEx

So I have this string and I want to parse it. Normally I would use string.split() for it but it's a bit complicated so I thought that may using regex is better in this case. But I am not too familar with regex. Maybe you girls/guys could help me out.

My string looks like this:

PING :sendak.freenode.net

Or like this

:username!~user@hostname.tld PRIVMSG #channelname :test

And should be parsed into it's components prefix, username, command, channel, text.

Example:

PING :sendak.freenode.net 

Should be:

prefix=[] username=[] command=[PING] channel=[] text=[sendak.freenode.net]

and the string:

:username!~user@hostname.tld PRIVMSG #channelname :test

should be parsed to:

prefix=[username!~user@hostname.tld] username=[username] command=[PRIVMSG] channel=[#channelname] text=[test]

In the end I have to fill out these variables:

message.prefix = "";
message.username = "";
message.command = "";
message.channel = "";
message.text = "";

I am spliting a line at a time!

Fairly obvious that it's gonna be a small IRC chat.

The problem I expierence is that it can start with a ":" but does not have to.Thus making it fairly complex to realising using several splits().

Thanks for any help!

I think this regex may help you: "(:?((. )![^ ] ))? ?([^ ] ) (#([^ ] ) )?(:(.*))?" :

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Message{
    public String prefix = "";
    public String userName = "";
    public String command = "";
    public String channel = "";
    public String text = "";

    public Message(String line){
        Matcher matcher = Pattern.compile("(:?((.*)![^ ]*))? ?([^ ]*) (#([^ ]*) )?(:(.*))?").matcher(line);
        if (matcher.matches()){
            prefix = matcher.group(2) != null? matcher.group(2): "";
            userName = matcher.group(3) != null? matcher.group(3): "";
            command = matcher.group(4) != null? matcher.group(4): "";
            channel = matcher.group(6) != null? matcher.group(6): "";
            text = matcher.group(8) != null? matcher.group(8): "";
        }
    }

    @Override
    public String toString() {
        return String.format("prefix=[%s] username=[%s] command=[%s] channel=[%s] text=[%s]", prefix, userName, command, channel, text);
    }
}


public class TestRegex {

    public static void main(String[] args) {
        System.out.println(new Message("PING :sendak.freenode.net"));
        System.out.println(new Message(":username!~user@hostname.tld PRIVMSG #channelname :test"));
        System.out.println(new Message("username!~user@hostname.tld PRIVMSG #channelname :test"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM