簡體   English   中英

拆分不帶空格的字符串

[英]Splitting a String without spaces

我有以下字符串,它由外部程序(OpenVAS)生成並作為字符串成功返回到我的程序。

<create_target_response id="b4c8de55-94d8-4e08-b20e-955f97a714f1" status_text="OK, resource created" status="201"></create_target_response>

我試圖拆分字符串給我“b4c8d .... 14f1”沒有引號。 我已經嘗試了各種各樣的轉義方法,並繼續獲取else方法“字符串不包含目標ID”。 我已經嘗試刪除IF語句檢查字符串,但繼續遇到相同的問題。 目標是將我的id字符串放入jTextField6。 String Lob包含如上所示的完整字符串。

     if (Lob.contains("id=\"")){
      // put the split here
           String[] parts = Lob.split("id=\"");
           String cut1 = parts[1];

           String[] part2 = cut1.split("\"");
           String TaskFinal = part2[0];

           jTextField6.setText(TaskFinal);

      }
       else {
           throw new IllegalArgumentException("String does not contain a Target ID");
       }

  } catch (IOException e) {
     e.printStackTrace();
  }

似乎我只需要逃避“而不是=(如果我這樣做,Java就會出錯)

提前致謝

編輯:現在使用jSoup lib的代碼 - 'id'字符串將不會顯示。 有任何想法嗎? 謝謝

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
          String TargIP = jTextField1.getText(); // Get IP Address
          String TargName = jTextField5.getText(); // Get Target Name
          String Vag = "8d32ad99-ac84-4fdc-b196-2b379f861def";
          String Lob = "";

  final String dosCommand = "cmd /c omp -u admin -w admin --xml=\"<create_target><name>" + TargName + "</name><hosts>" + TargIP + "</hosts></create_target>\"";
  3</comment><config id='daba56c8-73ec-11df-a475-002264764cea'/><target id='" + Vag + "'/></create_task>\"";
  final String location = "C:\\";
  try {
     final Process process = Runtime.getRuntime().exec(
        dosCommand + " " + location);
     final InputStream in = process.getInputStream();
     int ch;
     while((ch = in.read()) != -1) {
        System.out.print((char)ch);
       Lob = String.valueOf((char)ch);
       jTextArea2.append(Lob);


     }

  } catch (IOException e) {
     e.printStackTrace();
  }
           String id = Jsoup.parse(Lob).getAllElements().attr("id");
     System.out.println(id); // This doesn't output? 
}

這樣可以更輕松地獲得您的工作ID:

int idStart = Lob.indexOf("id=")+("id=\"").length();
System.out.println(Lob.substring(idStart,Lob.indexOf("\"",idStart)));

在“。”的基礎上拆分。您可以獲得所有關鍵值。

String str = "<create_target_response id=\"b4c8de55-94d8-4e08-b20e-955f97a714f1\" status_text=\"OK, resource created\" status=\"201\"></create_target_response>";
String[] tokens = str.split("\\\"");
System.out.println(tokens[1]);
System.out.println(tokens[5]);

輸出:

b4c8de55-94d8-4e08-b20e-955f97a714f1
201

在我看來,這比制作它簡單得多。 首先,拆分space ,然后檢查是否存在= 如果是,則在=split ,最后從第二個令牌中刪除"

棘手的一點是""內部的空間。 這將需要一些正則表達式,您可以從這個問題中解決

String input; // Assume this contains the whole string.
String pattern; // Have fun working out the regex.

String[] values = input.split(pattern);

for(String value : values)
{
    if(value.contains("=")) {
        String[] pair = value.split("=");
        String key = pair[0];
        String value = pair[1].replaceAll("\"");

        // Do something with the values.
    }
}

我的方法的優勢

如果提供的輸入遵循key="value" key="value"的格式,您可以解析通過的任何內容,而不是硬編碼屬性的名稱。

如果這是XML ..

然后使用XML解析器。 有一個很好的(很棒的)答案可以解釋為什么你不應該使用String操作來解析XML / HTML。 是答案。

您可以使用正則表達式來提取所需內容; 更重要的是,看起來id的值是UUID。 因此:

private static final Pattern PATTERN
    = Pattern.compile("\\bid=\"([^\"]+)\"");

// In code...
public String getId(final String input)
{
    final Matcher m = PATTERN.matcher(input);
    if (!m.find())
        throw new IllegalArgumentException("String does not contain a Target ID");
    final String uuid = m.group(1);
    try {
        UUID.fromString(uuid);

    } catch (IllegalArgumentException ignored) {
        throw new IllegalArgumentException("String does not contain a Target ID");
    }

    return uuid;
}

每個人都告訴你使用XML解析器(他們是對的),但沒有人告訴你如何。

開始:

String lob = ...

使用來自http://jsoup.org的 Jsoup,實際上是一個HTML解析器,但也整齊地處理XML:

String id = Jsoup.parse(lob).getAllElements().attr("id");
// b4c8de55-94d8-4e08-b20e-955f97a714f1

使用內置的Java XML API,不那么簡潔但沒有附加庫:

Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
    .parse(new InputSource(new StringReader(lob)));
String id = dom.getDocumentElement().getAttribute("id");
// b4c8de55-94d8-4e08-b20e-955f97a714f1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM