Java Best way to extract parts from a string

前端 未结 2 1133
旧巷少年郎
旧巷少年郎 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: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
    

提交回复
热议问题