Java查找两个字符之间的子字符串

3

我遇到了困难。我使用以下格式从字符串中读取玩家的名称:

"[PLAYER_yourname]"

我尝试了几个小时,都无法弄清楚如何读取“_”后面且在“]”之前的部分以获取其名称。
我可以得到一些帮助吗?我尝试使用子字符串、分割、正则表达式等方法,但都没有成功。谢谢! :)
顺便说一句:这个问题与其他问题不同,如果我按“_”拆分,我不知道如何在第二个括号处停止,因为我有其他字符串行超过了第二个括号。谢谢!

1
使用split方法string.split("-") - Saket Mittal
1
请展示一下你的努力? - Bacteria
你可以使用索引和 n-1 后解析。 - Brandon Ling
不,不是那样的。如果我分割字符串,我会超过第二个括号,因为同一行上有其他字符串。我该如何仅获取下划线后面且在右括号前的字符串? - SirTrashyton
1
@SaketMittal,那不是他想要的。 - Brandon Ling
1
确切的输入是什么? - Bacteria
6个回答

6

您可以进行以下操作:

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

谢谢!我没有想到使用那个,因为我不知道如何使用.indexOf或它的目的。我很感激! - SirTrashyton
1
如果这个答案解决了你的问题,那么你应该将它标记为正确答案。 - A.sharif
请记住,如果用户句柄/玩家名称包含“]”,则此方法将无效。您可以使用str.length - 1来解决这个问题。请注意,Zachary之前已经回答了这个问题,并且是完全相同的答案。 - Brandon Ling
@BrandonLing 或者使用lastIndexOf - Jean Logeart

4

您可以使用子字符串。 int x = str.indexOf('_') 返回 '_' 所在的字符,int y = str.lastIndexOF(']')返回 ']' 所在的字符。然后您可以执行 str.substring(x + 1, y),这将给您从该符号后到单词末尾的字符串,不包括关闭括号。


3

使用 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

我喜欢这个解决方案,因为它允许解决一般情况。 - rpax

2
这个解决方案使用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

请查看演示

图片描述在此


是的,它来自于regex101。虽然它没有Java正则表达式风格,但仍然可以作为一个有用的沙盒。 - MaxZoom

1
你可以这样做 -
public static void main(String[] args) throws InterruptedException {
        String s = "[PLAYER_yourname]";
        System.out.println(s.split("[_\\]]")[1]);
    }

输出:yourname

0

尝试:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接