2016-04-22 38 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")); 
    } 
} 
相关问题