Java Best way to extract parts from a string

前端 未结 2 1130
旧巷少年郎
旧巷少年郎 2020-12-21 14:34

I have the following string;

[Username [rank] -> me] message

The characters of the rank, username, and message will vary each time. What

相关标签:
2条回答
  • 2020-12-21 15:07
    String input = "[whatever [Is] -> me] Input";
    String user, rank, message;
    
    user = input.substring(1, input.indexOf('[', 1));
    rank = input.substring(input.indexOf('[', 1), input.indexOf(']'));
    message = input.substring(input.lastIndexOf(']'));
    

    this should work but if you really want it done right you should make a separate object that holds all this and can output it as a string. depends where this is coming from and where its going. -axon

    0 讨论(0)
  • 2020-12-21 15:29

    Use Java's support for regular expressions (java.util.regex) and let a regex match the 3 parts.

    For example this one: ^\[([\w]+) \[([\w]+)\] -> \w+\] (.*)$

    Java code snippet, slightly adapted from Ian F. Darwin's "Java Cookbook" (O'Reilly):

    import java.util.regex.*;
    
    class Test
    {
        public static void main(String[] args)
        {
            String pat = "^\\[([\\w]+) \\[([\\w]+)\\] -> \\w+\\] (.*)$";
            Pattern rx = Pattern.compile(pat);
            String text = "[Username [rank] -> me] message";
            Matcher m = rx.matcher(text);
            if(m.find())
            {
                System.out.println("Match found:");
                for(int i=0; i<=m.groupCount(); i++)
                {
                    System.out.println("  Group " + i + ": " + m.group(i));
                }
            }
        }
    }
    

    Output:

    Match found:
      Group 0: [Username [rank] -> me] message
      Group 1: Username
      Group 2: rank
      Group 3: message
    
    0 讨论(0)
提交回复
热议问题