我的目標是匹配第一個0和零後十進制值的所有內容。如果第一個小數位是零,那麼我也想匹配小數點。如果沒有小數點,則不捕獲任何數據。正則表達式積極lookbehind災難
這裏有我想要的一些例子:
180.57// should capture the "0123" on the end
180.570 // should capture the "0" on the end
180.// should capture the ".0123" on the end
180.0 // should capture the ".0" on the end
18// should capture nothing
180 // should capture nothing
如果小數點後第一位是0,則使得比賽很簡單:
(\.0.*)
我的問題是第一位小數時匹配地方不是0.我相信積極lookbehind將解決這個問題,但我無法讓它正常工作。這裏是我嘗試過的一個正則表達式:
(?<=^.*\..*)0.*
這個正則表達式最終將在Java中使用。
UPDATE:
我要使用這個表達式擺脫數字的和可能的小數點上使用Java的replaceAll
方法的字符串的結尾。我將通過用空字符串替換捕獲組來完成此操作。這是我想要的更好的例子。
String case1 = "180.570123";
String case2 = "180.570";
String case3 = "180.0123";
String case4 = "180.0";
String case5 = "180123";
String case6 = "180";
String result = null;
result = case1.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 180.57
result = case2.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 180.57
result = case3.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 180
result = case4.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 180
result = case5.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 18
result = case6.replaceAll("THE REGEX I NEED", "");
System.out.println(result); // should print 180
此外,我在http://gskinner.com/RegExr/
捕獲情況1錯誤,不捕捉的情況下2或者4。 – ubiquibacon 2012-03-02 14:10:20
@typoknig,已更新。案例1總是匹配正確。 *使用第一個捕獲組的內容,而不是整個匹配。* – Qtax 2012-03-02 14:14:39
啊,我明白了。正如你所說的那樣,在使用第一個捕獲組的內容時它似乎工作正常。非常感謝! – ubiquibacon 2012-03-02 14:54:04