I have the following string;
[Username [rank] -> me] message
The characters of the rank, username, and message will vary each time. What
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
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