I need to get the player's prefix, name and message from the string.
Usually the message looks like this:

? ??? [Prefix] Name? Message

Sometimes the first ? cleaned up

I compiled such a regular expression:

 .{0,}(\[.{0,}\])\1{0,} (.{0,})\?(.{0,}) 

And I use this code:

 System.out.println("[NChatBot] Processing chat line: " + msg); Matcher _m = _namePattern.matcher(msg); boolean found = false; while (_m.find()) { found = true; System.out.println("1: " + _m.group(1)); System.out.println("2: " + _m.group(2)); System.out.println("3: " + _m.group(3)); } if (!found) { System.out.println("Can't parse!"); } 

But every time I get the output:

[STDOUT]: [NChatBot] Processing chat line: ??? [Player] Playername? msg
[STDOUT]: Can't parse!

Where is the mistake?

1 answer 1

The following code finds the required values:

 String msg = "? ??? [Префикс] Имя ? Сообщение"; Pattern _namePattern = Pattern.compile("(\\[[^\\]\\[]*])\\s+(.*?)\\s*\\?\\s*(.*)"); Matcher _m = _namePattern.matcher(msg); boolean found = false; while(_m.find()) { found = true; System.out.println("1: "+_m.group(1)); System.out.println("2: "+_m.group(2)); System.out.println("3: "+_m.group(3)); } if(!found) { System.out.println("Can't parse!"); } 

Details :

  • (\\[[^\\]\\[]*]) - (group №1) a substring of the type [...]
  • \\s+ - 1 or more whitespace characters
  • (.*?) - (group number 2) 0 or more of any characters, the smallest number to the first ...
  • \\s*\\?\\s* - the sign ? inside 1 or more space characters
  • (.*) - (group number 3) the rest of the line to the end.