gpt4 book ai didi

java - 拆分有限制的字符串

转载 作者:行者123 更新时间:2023-11-30 08:02:08 25 4
gpt4 key购买 nike

我想拆分一个字符串,但我想拆分它删除不等于指定数字的数字,当然还有它后面的字符。

这是我的代码:

public static void main(String[] args) throws IOException {
String x = "32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X";
System.out.println(splittedArray(x, "\\s(?<!32)\\s").toString());
// I know this regex is completely wrong.
}

private static List<String> splittedArray(String str, String regex) {
return Arrays.asList(str.split(regex));
}

更好的解释:

示例:

32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X

如果我想要所有 32 个数字和后面的字符,它应该返回:

32 X or 32X // Whatever
32 X
32 Y
32 X
32 X

我坚持让它发挥作用,我们将不胜感激。

最佳答案

我会使用 Pattern 来解决它和 Matcher ,而不是尝试拆分字符串。

编辑:更新代码以显示如何收集到 List<String> 中并转换为 String[]如果需要的话。

public static void main(String[] args)
{
// the sample input
String x = "32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X";

// match based upon "32". This specific match can be made into
// a String concat so the specific number may be specified
Pattern pat = Pattern.compile("[\\s]*(32\\s[^\\d])");

// get the matcher
Matcher m = pat.matcher(x);

// our collector
List<String> res = new ArrayList<>();

// while there are matches to be found
while (m.find()) {
// get the match
String val = m.group().trim();
System.out.println(val);

// add to the collector
res.add(val);
}

// sample conversion
String[] asArray = res.toArray(new String[0]);
System.out.println(Arrays.toString(asArray));
}

基于样本输入的返回输出:

32 X
32 X
32 Y
32 X
32 X
[32 X, 32 X, 32 Y, 32 X, 32 X]

关于java - 拆分有限制的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37151189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com