【问题标题】:Java String separation [closed]Java字符串分离[关闭]
【发布时间】:2013-02-07 18:35:23
【问题描述】:

我被困在试图获得所需的输出。它实际上是我在另一个问题中面临的一个字符串分离问题。

// 输入 String input1 = "=DIVIDE(Input!RC,Input!R[1]C)"; // B1 String input2 = "=DIVIDE(MULTIPLY(Input!R[-1]C,Input!R[1]C),100)"; // B2 字符串 input3 = "=Input!R[-2]C + R[-1]C"; // B3 String input4 = "=DIVIDE(R[-2]C,Input!R[-2]C)"; // B4 字符串输入5 = "=R[-4]C+R[-1]C"; // B5

现在,我必须用适当的 B 值替换 RC。

输入 5 的示例,我将查看 R[-4]C,然后由于它的输入 5,我将添加 (-4) 和 (5) 以获得 1,并将 R[-4]C 替换为 B1。

对所有人来说都是一样的。

// 期望的输出 // =DIVIDE(输入!B1,输入!B2) // =除法(乘法(输入!B1,输入!B3),100) // =输入!B1+计算!B2 // =DIVIDE(calc!B2,Input!B2) // =calc!B1+calc!B4

谁能告诉我如何实现这一目标?

【问题讨论】:

  • 可以有两位数吗?
  • 你有没有尝试过?
  • 使用正则表达式查找RC或R[(\d)]C,提取数字并添加到你想要的值。
  • 你可能想看看真正的解析器(词法分析器),对我来说这看起来像是一种语言,而不仅仅是字符串操作......
  • 我在这里处理谷歌电子表格 api,是的,我已经尝试过了,但我想从其他人那里得到一些想法。

标签: java string stringbuilder stringtokenizer


【解决方案1】:

这里有一些想法:

identify offset (1 for input1, 2 for input2 etc)
for each match of "R" ( "[" DIGIT+ "]" )? "C"
  if DIGIT+ != "" then <index> = offset + tonumber(DIGIT+) else <index> = offset
  replace match with B<index>

【讨论】:

    【解决方案2】:

    这就是想法

    static String replaceB(String s, int n) {
        Matcher m = Pattern.compile("\\W(R(\\[(.+?)\\])?C)").matcher(s);
        for (; m.find(); m.reset(s)) {
            String r = "B" + (m.group(3) == null ? n : n + Integer.parseInt(m.group(3)));
            if (!r.startsWith("!")) {
                r = "calc!" + r;
            }
            s = s.replace(m.group(1), r);
        }
        return "B" + n + s;
    }
    
    public static void main(String args[]) throws Exception {
        String input1 = "=DIVIDE(Input!RC,Input!R[1]C)"; // B1
        String input2 = "=DIVIDE(MULTIPLY(Input!R[-1]C,Input!R[1]C),100)"; // B2
        String input3 = "=Input!R[-2]C + R[-1]C"; // B3
        String input4 = "=DIVIDE(R[-2]C,Input!R[-2]C)"; // B4
        String input5 = "=R[-4]C+R[-1]C"; // B5
        System.out.println(replaceB(input1, 1));
        System.out.println(replaceB(input2, 2));
        System.out.println(replaceB(input3, 3));
        System.out.println(replaceB(input4, 4));
        System.out.println(replaceB(input5, 5));
    }
    

    打印

    B1=DIVIDE(Input!B1,Input!B2)
    B2=DIVIDE(MULTIPLY(Input!B1,Input!B3),100)
    B3=Input!B1 + calc!B2
    B4=DIVIDE(calc!B2,Input!B2)
    B5=calc!B1+calc!B4
    

    【讨论】:

    • 对不起,我已经编辑了问题中的输入和输出部分,请检查。我的错。
    • 已修复,现在看起来很像你的
    • 对不起,我再次进行了更改。这是输入错误。现在我有一个正确的输入。当 RC 之前没有任何内容时,它会附加 calc!给它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多