2016-04-22 25 views
0

我想寫一個程序,讀取以下輸入分離:Java的一個單詞,可能會或可能不會受到空間

<repeat value="2" content="helloworld"/> 

現在我需要分析和存儲「重複」,「2 '和'helloword'在不同的變量。到現在爲止還挺好。問題在於輸入中的任何地方都可能存在空格,這使得任務顯得更加困難,超出了我的能力。我想也許使用正則表達式,但我無法工作,我對這個主題的研究沒有結果。那麼,這將是一個聰明的方法來做到這一點?

例子:

< rep eat va lue=" 2" conte nt= "helloworld"/> 

馬赫

repeat, 2, helloworld 
+2

這個? '(?<= <)(\ w +)| \ w + =「(\ w +)」',[DEMO](https://regex101.com/r/vE2xQ6/1) –

+5

你想要檢索什麼?標籤的名稱和每個屬性的值?您很可能會從使用XML解析器中受益。 – Aaron

+0

https://regex101.com/r/hU0eE2/1 – rock321987

回答

1

使用此正則表達式來涵蓋所有可能的間距:

<\s*(\w+)\s+value\s*=\s*"(\w+)"\s*content\s*=\s*"(\w+)"\s*\/\s*> 

這將你給的例子,回報整個字符串匹配標籤(第1組),值(第2組)和內容(第3組)。

Test it online at regex101.com


更新:

,甚至讓該關鍵字內部空間valuecontent,你可以簡單地添加一個\s*每間(匹配任意數量的空白字符,包括零)字母:

<\s*(.+)\s+v\s*a\s*l\s*u\s*e\s*=\s*"(\w+)"\s*c\s*o\s*n\s*t\s*e\s*n\s*t\s*=\s*"(.+)"\s*\/\s*> 

Test it online at regex101.com

+0

感謝@ByteCommander,但我們可以更進一步 - 匹配我想匹配的詞語,即使它們中有空格。編輯我的問題以獲得更多解釋。 – Alex

+0

@Alex您可以在所有字母之間添加'\ s *'。更新了我的答案。如果它解決了你的問題,也不要忘記接受它。 –

0

我建議你使用DOM解析器,例如Jsoup。 當然輸入應該是有效的xml/html

package com.example; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.select.Elements; 

public class AttributesReader { 
    public static void main(String[] args) throws Exception { 
     String xmlStrMessage="<repeat value=\"2\" content=\"helloworld\"/>"; 
     Document doc = Jsoup.parse(xmlStrMessage); 
     Elements repeat = doc.select("repeat"); 
     System.out.println("value:"+repeat.attr("value")); 
     System.out.println("content:"+repeat.attr("content")); 
    } 
} 
相關問題