2013-05-09 177 views
2

我正在用這個拉我的頭髮。在括號或逗號前面加上字符的正則表達式

說我有一個字符串7f8hd::;;8843fdj fls "": ] fjisla;vofje]]} fd)fds,f,f

我想根據該字符串無論是}],)但所有這些字符可能是目前我結束的前提下,現在提取這種7f8hd::;;8843fdj fls "":從字符串只需要第一個。

我試過沒有成功創建一個匹配器和模式類的正則表達式,但我似乎無法做到正確。

我能想到的最好的是在下面,但我的法律程序只是似乎沒有像我認爲應該的工作。

String line = "7f8hd::;;8843fdj fls "": ] fjisla;vofje]]} fd)fds,f,f"; 
Matcher m = Pattern.compile("(.*?)\\}|(.*?)\\]|(.*?)\\)|(.*?),").matcher(line); 
while (matcher.find()) { 
    System.out.println(matcher.group()); 
} 

我很明顯沒有正確理解reg exp。任何幫助都會很棒。從字符串的開頭

回答

5
^[^\]}),]* 

比賽直到(但不包括)第一]}),

在Java:

Pattern regex = Pattern.compile("^[^\\]}),]*"); 
Matcher regexMatcher = regex.matcher(line); 
if (regexMatcher.find()) { 
    System.out.println(regexMatcher.group()); 
} 

(實際上,你可以刪除反斜槓([^]}),]),但我想,讓他們有清楚和兼容性,因爲並非所有的正則表達式引擎識別的成語。)

說明:

^   # Match the start of the string 
[^\]}),]* # Match zero or more characters except ], },) or , 
+0

你忘了逗號。 :)添加它請。 – Kent 2013-05-09 14:32:47

+0

正是我想要的。簡單而重要。您沒有添加問題中所述的逗號事件,但這樣做確實很麻煩。 – Gareth 2013-05-09 14:33:56

3

你可以只通過replaceAll削減剩餘部分:

String newStr = yourStr.replaceAll("[\\])},].*", ""); 

split()並獲得第一個元素。

String newStr = yourStr.split("[\\])},]")[0]; 
+0

This works ....謝謝 – 2017-10-12 17:57:50

1

你能嘗試正則表達式(.*?)[}\]),](.*?)我測試rubular和對你的代碼工作。

1

你可以使用這個(如Java字符串):

"(.+?)[\\]},)].*" 

這裏是一個fiddle

+0

該網站的+1。從來不知道它存在。真棒。 – Gareth 2013-05-09 14:48:31

+0

thx。是的,它有時非常方便。 – luksch 2013-05-09 14:49:52

相關問題