我想弄清楚一個正則表達式可以用於java的String.split(正則表達式),以便從文件中獲取「行」數組。正則表達式滿足3個不同的情況
回車沒有定義行的結束,而是一個逗號 - 但不是所有的逗號。如果逗號在括號,單引號或註釋(/ *註釋,更多註釋* /)之間,則不表示行的結尾。
例子:
1 test fixed(5,2),
2 another_test char(12),
2 a_third_test,
3 one pic'9{9}V.99',
3 two pic'9,999V.99',
3 three fixed(7,2),
/* test,t*/
/*test 2,*/
/*and more */
2 another_field fixed bin(13),
2 a_really_long_super_long_field_name_requiring_two_lines_for_declaration
char(1),
2 a_field char(8);
預期的輸出是(與\ T和額外的空格省略清晰):
1 test fixed(5,2)
2 another_test char(12)
2 a_third_test
3 one pic'9{9}V.99'
3 two pic'9,999V.99'
3 three fixed(7,2)
/* test,t*//*test 2,*//*and more */ 2 another_field fixed bin(13)
2 a_really_long_super_long_field_name_requiring_two_lines_for_declaration
char(1)
2 a_field char(8)
我拿出3個獨立的正則表達式來獲得3件:
,(?![^(]*\))
- 所有的逗號括號 不
(,(?![^']*'))
- 所有逗號不是單引號(,(?![^\/\*]*\*\/))
- 沒有評論所有逗號
我試着用或(.*?)|(,)|'.*?'|(,)|\/*.*?*\/|(,)
加入他們,但得到如下:
1 test fixed
2 another_test char
2 a_third_test
3 one pic
3 two pic
3 three fixed
2 another_field fixed bin
2 a_really_long_super_long_field_name_requiring_a_line_break_... char
2 a_field char
是有一種方法可以將這3個正則表達式(或者是否有更好的表達式)進行組合,以找到滿足所有3個的組?
UPDATE:
我可以完成確切的事情了一些簡單的Java,但我想用正則表達式來做到這一點作爲一個學術化追求。
String temp = "";
for(String line:text.split("\n")){
if(line.trim().charAt(line.trim().length()-1) == ',' || line.trim().charAt(line.trim().length()-1) == ';'){
System.out.println(temp + line);
temp = "";
} else {
temp += line.trim();
}
}
這是或運營商可能幫助? – jdv
這是我嘗試使用的第一件事,使用\(。*?\)|(,)|'。*?'|(,)| \/\ *。*?\ * \/|(,) 我得到: '1測試固定 2個another_test焦炭 2 a_third_test 3單張影像 3兩PIC 3三個固定 2 another_field固定倉 2 a_really_long_super_long_field_name_requiring_two_lines ...燒焦 2 a_field char' – gooeylewie
這就是應該在問題的主體中的那種東西。 – jdv