Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Java Best way to extract parts from a string

I have the following string;

[Username [rank] -> me] message

The characters of the rank, username, and message will vary each time. What is the best way I can break this into three separate variables (Username, rank and message)?

I have experimented with:

String[] parts = text.split("] ");

But it is throwing back errors. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...