Java 查找字符之间的子串

Java Find Substring Inbetween Characters

我很卡。我使用这种格式来读取字符串中的玩家姓名,如下所示:

"[PLAYER_yourname]"

我已经尝试了几个小时,但无法弄清楚如何只读取“_”之后和“]”之前的部分来获取名称。

需要我帮忙吗?我玩弄了子字符串、拆分、一些正则表达式,但没有运气。谢谢! :)

顺便说一句:这个问题是不同的,如果我用 _ 分割我不知道如何在第二个括号停止,因为我有其他字符串行超过第二个括号。谢谢!

您可以使用子字符串。 int x = str.indexOf('_') 为您提供“_”所在的字符,int y = str.lastIndexOF(']') 为您提供“]”所在的字符。然后你可以做 str.substring(x + 1, y) ,这会给你从符号之后到单词结尾的字符串,不包括右括号。

你可以这样做:

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

你可以这样做 -

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

output: yourname

尝试:

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

此解决方案使用 Java 正则表达式

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

DEMO

使用 regex 匹配器函数你可以做到:

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));

结果:

yourname

解释:

\[ 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