简体   繁体   English

Java查找字符串中间字符串

[英]Java Find Substring Inbetween Characters

I am very stuck. 我很困惑。 I use this format to read a player's name in a string, like so: 我使用这种格式来读取字符串中的播放器名称,如下所示:

"[PLAYER_yourname]"

I have tried for a few hours and can't figure out how to read only the part after the '_' and before the ']' to get there name. 我已经尝试了几个小时,无法弄清楚如何只读取'_'之后和']'之前的部分来获取名称。

Could I have some help? 我可以帮忙吗? I played around with sub strings, splitting, some regex and no luck. 我玩子字符串,分裂,一些正则表达式,没有运气。 Thanks! 谢谢! :) :)

BTW: This question is different, if I split by _ I don't know how to stop at the second bracket, as I have other string lines past the second bracket. 顺便说一句:这个问题是不同的,如果我分开_我不知道如何停在第二个括号,因为我有其他字符串线经过第二个括号。 Thanks! 谢谢!

You can do: 你可以做:

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

You can use a substring. 您可以使用子字符串。 int x = str.indexOf('_') gives you the character where the '_' is found and int y = str.lastIndexOF(']') gives you the character where the ']' is found. int x = str.indexOf('_')为您提供找到'_'的字符, int y = str.lastIndexOF(']')为您提供找到']'的字符。 Then you can do str.substring(x + 1, y) and that will give you the string from after the symbol until the end of the word, not including the closing bracket. 然后你可以做str.substring(x + 1, y) ,它会给你从符号后面的字符串直到单词的结尾,不包括结束括号。

Using the regex matcher functions you could do: 使用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));

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

This solution uses Java regex 此解决方案使用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

see DEMO DEMO

在此输入图像描述

You can do like this - 你可以这样做 -

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

output: yourname 输出:你的名字

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM