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!
source to share
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.
source to share
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
source to share