如何跳过Java中的一部分行 - 不知道我在做什么

时间:2017-11-08 18:29:16

标签: java regex string

我只需要在一串数字中使用其他所有数字。 这就是xml文件内容的来源,但我只想使用第一组,然后是每个其他组。 每组中的第二个数字可以忽略。最重要的数字是第一个,如1,3,5和29 你能帮我吗?每组等于“x”:“x”,

<CatcList>{“1":"15","2":"15","3":"25","4":"25","5":"35","6":"35","29":"10","30":"10"}</CatcList> 

现在我的脚本看起来像这样,但我不是那个写它的人。

我只包括了需要的部分。 StartPage将是使用的变量。 如果您知道如何将1添加到EndPage Integer,那么这也是非常有用的。 谢谢!

 Util.StringList xs;
 line.parseLine(",", "", xs);
 for (Int i=0; i<xs.Size; i++) {
   Int qty = xs[i].right(xs[i].Length - xs[i].find(":")-1).toInt()-1;
   for (Int j=0; j<qty; j++) {
      Output_0.File.DocId = product;
      Output_0.File.ImagePath = Image;
      Output_0.File.ImagePath1 = Image;
  Output_0.File.StartPage = xs[i].left(xs[i].find(("-"))).toInt()-1;
  Output_0.File.EndPage = xs[i].mid(xs[i].find("-")+1, (xs[i].find(":") - xs[i].find("-")-1)).toInt()-0;
      Output_0.File.Quantity = qty.toString();
      Output_0.File.commit();

3 个答案:

答案 0 :(得分:0)

试试这个:

,?("(?<num>\d+)":"\d+"),?("\d+":"\d+")?

名为num的组将包含“x”的第一部分的所有其他出现:“x”

所以对于值:

"1":"14","2":"14","3":"14","4":"24","5":"33","6":"44","7":"55"

名为'num'的组将包含1 3 5和7。

see example here

编辑:提取数字后,您可以根据需要进行操作:

Pattern datePatt = Pattern.compile(",?(\"(?<num>\\d+)\":\"\\d+\"),?(\"\\d+\":\"\\d+\")?");
String dateStr = "\"1\":\"14\",\"2\":\"14\",\"3\":\"14\",\"4\":\"24\",\"5\":\"33\",\"6\":\"44\",\"7\":\"55\"";
Matcher m = datePatt.matcher(dateStr);

while (m.find()) {          
    System.out.printf("%s%n", m.group("num"));           
}

答案 1 :(得分:0)

您可以将Pattern与循环和某些条件一起使用来提取此信息:

String string = "<CatcList>{\"1\":\"15\",\"2\":\"15\",\"3\":\"25\",\"4\":\"25\","
        + "\"5\":\"35\",\"6\":\"35\",\"29\":\"10\",\"30\":\"10\"}</CatcList> ";
String regex = "\"(\\d+)\":\"\\d+\"";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
int index = 0;
while (matcher.find()) {
    if (index % 2 == 0) {//From your question you have to get alternative results 1 3 5 ...
        System.out.println(matcher.group(1) + " ---> " + matcher.group());
    }
    index++;
}

<强>输出

1 ---> "1":"15"
3 ---> "3":"25"
5 ---> "5":"35"
29 ---> "29":"10"

正则表达式"(\d+)":"\d+"应匹配"number":"number"我使用(\d+)的任意组合,因此我只能获取该组的信息。

答案 2 :(得分:0)

该XML值看起来像JSON映射。所有.right,.mid和.left代码对我来说都很混乱,没有关于这些方法如何工作的细节。这样的事情似乎更清楚:

// leaving out all the backslash escapes of the embedded quotes
String xmlElement = "{"1":"15","2":"15","3":"25","4":"25","5":"35","6":"35","29":"10","30":"10"}";
xmlElement = xmlElement.replaceAll("[}{]", "");
String[] mapEntryStrings = xmlElement.split(","); 
Map<Integer, String> oddStartPages = new HashMap<Integer, String>();
for (String entry : mapEntryStrings) {
    String[] keyAndValue = entry.split(":");
    int key = Integer.parseInt(keyAndValue[0]);
    if (key % 2 == 1) {// if odd 
        oddStartPages.put(key, keyAndValue[1]);
    }
}

然后,oddStartPages Map中的一组键恰好是&#34;第一个和所有其他组中的第一个数字的集合&#34;要求。