Java Find substring between characters

I am very stuck. I use this format to read the player's name in a string, for example:

"[PLAYER_yourname]"

      

I've tried for hours and can't figure out how to read only the part after "_" and before "]" to get the title there.

Can I help? I've played around with helper strings, splitting, some regex, and with no luck. Thank you! :)

BTW: This question is different if I split by _ I don't know how to stop at the second parenthesis since I have other string lines outside the second parenthesis. Thank!

+3


source to share


6 answers


You can do:



String s = "[PLAYER_yourname]";
String name = s.substring(s.indexOf("_") + 1, s.lastIndexOf("]"));

      

+6


source


You can use a substring. int x = str.indexOf('_')

gives you the character that "_" is in and int y = str.lastIndexOF(']')

gives you the character that "]" is in. Then you can do str.substring(x + 1, y)

and that will give you the line after the character until the end of the word, not counting the closing parenthesis.



+4


source


Using the regex

-server functions you could do:

String s = "[PLAYER_yourname]";
String p = "\\[[A-Z]+_(.+)\\]";

Pattern r = Pattern.compile(p);
Matcher m = r.matcher(s);

if (m.find( ))
   System.out.println(m.group(1));

      

Result:

yourname

      

Explanation:

\[ matches the character [ literally

[A-Z]+ match a single character (case sensitive + between one and unlimited times)

_ matches the character _ literally

1st Capturing group (.+) matches any character (except newline)

\] matches the character ] literally

      

+3


source


This solution uses Java regex

String player = "[PLAYER_yourname]";
Pattern PLAYER_PATTERN = Pattern.compile("^\\[PLAYER_(.*?)]$");
Matcher matcher = PLAYER_PATTERN.matcher(player);
if (matcher.matches()) {
  System.out.println( matcher.group(1) );
}

// prints yourname

      

see DEMO

enter image description here

+2


source


You can do this:

public static void main(String[] args) throws InterruptedException {
        String s = "[PLAYER_yourname]";
        System.out.println(s.split("[_\\]]")[1]);
    }

      

output: your name

+1


source


Try:

Pattern pattern = Pattern.compile(".*?_([^\\]]+)");
Matcher m = pattern.matcher("[PLAYER_yourname]");
if (m.matches()) {
  String name = m.group(1);
  // name = "yourname"
}

      

0


source







All Articles