2013-10-31 36 views
0

我沒有在java中使用正則表達式的經驗,但我認爲我們可以使用regexp解決這個問題,它可以比我的示例更容易。 我有一個帶有雙||符號的文本。文本可以看起來像:
1)aaa||bbb||ccc
2)aaa||||ccc
3)||bbb||ccc
4)|| ||cccc
我想後提取文本第一|| - BBB,之後第二||安德烈 - ccc。我做了:提取「||」之間和之後的文本的正則表達式符號

Pattern p = Pattern.compile("||",Pattern,DOTALL); 
String types[] = p.split(stringToParse); 

但是當字符串沒有3個部分時這不起作用。

二的想法是:

Pattern p = Pattern.compile("||",Pattern,DOTALL); 
Matcher m= p.matcher(strToParse); 
while (m.find()) { 
System.out.println(m.group() + " " + m.start() + " " + m.end()); 
} 

然後我知道當|| occures並且是可以做到的字符串。 是否存在更簡單更簡單的方法來解決這個問題?

+7

不要!使用[HTML解析器](http://stackoverflow.com/questions/2168610/which-html-parser-is-best) – Maroun

+1

會在包含輸入工作的String對象上使用split(「
」)?這爲您提供了一個數組,其中包含標記之前,之間和之後的文本標記。缺點是,如果你的輸入是HTML頁面,你將會在開始和結束時結束一個巨大的令牌。 – Izmaki

+1

什麼Maroun Maroun說,和[這](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags?lq=1)。 – Mena

回答

0

如上所述人們說不要將它用於HTML解析器。

Pattern p = Pattern.compile("(<br>)\\w*(<br>)"); 
Matcher m= p.matcher(c); 
while (m.find()) { 
System.out.println(m.group().replace("<br>", ""));// replace <br>. 
} 
0

此:

String[] data = { 
     "aaa||bbb||ccc", 
     "aaa||||ccc", 
     "||bbb||ccc", 
     "|| ||cccc" 
}; 
for (String string : data) { 
    String[] split = string.split(Pattern.quote("||")); 
    System.out.println("0:"+split[0] + ", 1:" + split[1] + " 2:" + split[2]); 
} 

給出:

0:aaa, 1:bbb 2:ccc 
0:aaa, 1: 2:ccc 
0:, 1:bbb 2:ccc 
0:, 1: 2:cccc 

注意事項使用Pattern.quote()正則表達式的轉義,因爲|special regex characters

0

您誤解了分裂的文檔。 這將拆分字符串上stringToParse之間:

String types[] = between.split(stringToParse); 

你可能想在定點分裂之間的串stringToParse:

String types[] = stringToParse.split(between); 

例如:

String s = "a:b:c"; 
String letters[] = s.split(":"); 
相關問題