Java 特定的子字符串

Java specific substring

我有以下形式的字符串:

1x Intel Celeron G1850*

如何获取仅包含 "Intel Celeron G1850" 的子字符串? - 我正在考虑在 x 和 *

之间拆分

子字符串是一个不错的选择。不是分裂。因为复杂。

String str = "1x Intel Celeron G1850*";
str.substring(str.indexOf("x"), str.length() -1)

如果你想对这一个(或极少数)String 做,你的方法绝对没问题。 "mass wise" 将编译一个 "RegExp" 并匹配你的(统一的和许多)字符串。

像这样:

    Pattern pattern = Pattern.compile("^\d+x (.+)\*$");
    Matcher matcher = pattern.matcher("1x Intel Celeron G1850*");
    if (matcher.matches()) {
        System.out.println(matcher.group(1));
    }

这个答案将处理 1x 的可变长度。我假设每条记录的单位数中没有 x 个字符。我还假设每条记录的格式相同

str.substring(str.indexOf('x') + 2);

这将获取所有内容 ,包括 之后 x 的索引位置加上 2 个索引,这些索引将把它放在 space 之后的第一个字母上.

1x Intel Celeron G1850

将导致

Intel Celeron G1850

这个:

1000x Intel Celeron G1850

结果相同