java复制两个特殊字符之间的字符串与split

时间:2018-04-22 15:48:23

标签: java android

   String Code = "[123456]Ahmed"
 String[] code_after_Cut = code.split("\\]" , "\\[");

我需要削减" 123456"来自代码字符串

3 个答案:

答案 0 :(得分:1)

您可以分两步尝试。顺便说一句,你在代码中有一个大写字母c

 public static void main(String args[]) {
    String code = "[123456]Ahmed";
    System.out.println("code : " + code.split("\\]")[0].split("\\[")[1]);

    //or with regex it can goes like this
    Pattern patern = Pattern.compile("([0-9]{6})");
    Matcher matcher = patern.matcher(code);
    while (matcher.find()) {
        System.out.println("code: " + matcher.group(1));
    }
 }

答案 1 :(得分:0)

// as @RealSkeptic says... Regular expressions might be your point...
import java.until.regex.*;

....

String code = "[123456]Ahmed";
Pattern P = Pattern.compile("\\[(\\d+?\\)]Ahmed");
Matcher m = P.matcher(code);
String numberStr = null;
if (m.find()) numberStr = m.group(1);
// should print: 123456

答案 2 :(得分:0)

我不认为,它的名字总是“艾哈迈德”所以我会推荐这个:

    val full = "[123456]Achmed"
    val pattern = Pattern.compile("\\[([0-9]*)\\].*")
    val matcher = pattern.matcher(full)
    if (matcher.matches())
        Log.d("TAG", matcher.group(1))