试图将多个String解析为1个String

时间:2017-07-12 12:06:07

标签: java parsing

我试图从一个长字符串中提取2个特定的数据。这两个值都在" ="之后,但问题是我不能仅仅在每个" ="上分割数据。因为我需要的一些数据也包含它们:

example: "{col1=RND393JKDN, col2=DJW//39ndo==8}
desired format: "RND393JKDN, DJW//39ndo==8" 

下面是我为修复而编写的代码,但另一部分是我不确定将输入多少列,所以我必须能够处理未知数量的列,如:{{1 }}

"{col1=value1, col2=value2, col3=value3}"

4 个答案:

答案 0 :(得分:1)

如果可能,请考虑更改输入格式。如果没有,这是一个天真而简单的方法。

import java.util.List;
import java.util.ArrayList;



public class HelloWorld
{
  public static void main(String[] args)
  {
    String s = "{col1=RND393JKDN, col2=DJW//39ndo==8}";
        s=s.substring(1, s.length()-1); //remove {}
        s.replaceAll(" ", "");
        String[] explode = s.split(",");
        List<String> result = new ArrayList<String>();
        for (int i=0; i<explode.length; i++) {
            String keyAndValue = explode[i];
            int at = keyAndValue.indexOf("=");
            String value = keyAndValue.substring(at+1);
            result.add(value);
        }
        String finalResult = "";
        for (String val : result) {
            finalResult+=val+", ";
        }
        finalResult=finalResult.substring(0, finalResult.length()-2);
        System.out.println(finalResult);
  }
}

基本上,闯入键+值标记,找到first = char并从那里获取值。很简单。除非有其他一些意想不到的格式规则。我希望空格和逗号不会出现在键和值中。

答案 1 :(得分:1)

正则表达式是一件很棒的事情。下面是一个示例,说明如何使用Java的内置MatcherPattern类以简单的方式完成所需的操作。

public static void main(String[] args)
{
    String input = "{col1=RND393JKDN, col2=DJW//39ndo==8}";
    //Remove the {}
    str = str.substring(1, str.length() - 1);
    //Match "col", then any number, then an = sign,
    //then capture everything from the = to the , as "content"
    Pattern p = Pattern.compile("col\\d+=(?<content>[^,]+)");
    Matcher m = p.matcher(str);
    //The target string.
    String out = "";
    //While a match for the pattern exists, i.e. do for all matches of the pattern.
    while (m.find())
    {
        //String together desired parts into the output string, separated by ", "
        out += m.group("content") + ", ";
    }
    //Remove trailing ", "
    out = out.substring(0, out.length() - 2);
}

答案 2 :(得分:0)

为自己建立一个=职位列表。根据您需要的数量,构建子串(您已经这样做了)。

答案 3 :(得分:0)

我用逗号分割原始字符串,然后替换this.SuspendLayout(); // Bulk add the elements to the Form controls. this.ResumeLayout(); 前面的内容:

=