【问题标题】:How to Split a String without deleting split character如何在不删除拆分字符的情况下拆分字符串
【发布时间】:2020-04-09 03:47:19
【问题描述】:

我想将String 拆分为多个部分,但是拆分字符串时不应删除该字符。

在我的示例中,我想要输出:

parts[0]= 4x
parts[1]= -3y
parts[2]= 6z
parts[3]= 3v

这是我的代码:

import java.util.Arrays;

public class Polynomaddition {

public static void main(String[] args) {
    String fraction = "4x-3y+6z+3v";
    String [] parts = fraction.split("(?<=\\[a-z]");
    System.out.println(Arrays.toString(parts));
    //String result = calculator(fraction);
}

public static String calculator(String s) {
    String result = "";
     String [] parts = s.split("(?<=[a-z])", -1);

    return result;
    }
}

【问题讨论】:

  • "(?&lt;=[a-z])" 没有 -1 很好。

标签: java arrays string split substring


【解决方案1】:

解决方案 1

在您的情况下,您似乎想要这个正则表达式 \+|(?=-)

String[] parts = fraction.split("\\+|(?=-)");

详情

  • 拆分为
  • \+加号
  • |
  • (?=-) 减去而不删除它

解决方案 2

或者使用您的正则表达式,但您需要检查每个结果,例如:

String[] parts = Arrays.stream(fraction.split("(?<=[a-z])"))
        .map(s -> s.startsWith("+") ? s.substring(1, s.length()) : s)
        .toArray(String[]::new);

输出

[4x, -3y, 6z, 3v]

【讨论】:

    【解决方案2】:

    我根本不会使用split。相反,使用匹配实际多项式项的模式,并使用 Matcher,特别是其 findgroup 方法来提取每个匹配项:

    List<String> parts = new ArrayList<>();
    
    Matcher termMatcher = Pattern.compile("[-+]?\\d+[a-z]").matcher(fraction);
    while (termMatcher.find()) {
        String part = termMatcher.group();
        if (part.startsWith("+")) {
            part = part.substring(1);
        }
        parts.add(part);
    }
    
    System.out.println(parts);
    

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多