我想匹配的東西和我的生活我無法弄清楚爲什麼它不能按預期工作。爲什麼Pattern不能匹配「/ *!」?
字符串:"/*! preserved */"
模式:
Pattern.compile("(/[*][!](?:.+?)[*]/)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
- FAIL
模式:
Pattern.compile("(/[*](?:.+?)[*]/)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
- PASS
我只是想趕上開幕註釋字符串之後有一個!
意見。我甚至嘗試降低比賽剛剛/*!
:
Pattern.compile("(/[*][!])", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
- FAIL
Pattern.compile("(/[*!]{2})", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
- FAIL
Pattern.compile("(/[*][!])", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
- FAIL
Java Version "1.6.0_43"
Java(TM) SE Runtime Environment (build 1.6.0_43-b01)
Java HotSpot(TM) 64-Bit Server VM (build 20.14-b01, mixed mode)
編輯
此操作失敗,這沒有任何意義對我來說,因爲我的模式沒有開始或要求結束:
Pattern p = Pattern.compile("(/[*]!.+?[*]/)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("this is a test /*! preserved */ this is a test /*! preserved1 */");
System.out.println("Pattern: " + p);
System.out.println("Group: " + m.group(1));
System.out.println("Found: " + m.find());
即使減少它只是匹配/*!
失敗:
Pattern p = Pattern.compile("(/[*]!)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("this is a test /*! preserved */ this is a test /*! preserved1 */");
System.out.println("Match: " + m.find());
System.out.println("Pattern: " + p);
System.out.println("Group: " + m.group(1));
'*'是一個特殊字符,像這樣轉義它'''*'' – Doorknob 2013-05-12 03:03:26
@ doorknob將'*'放在'[]'中,就像他做的一樣,它使它匹配一個字面的'*'。 – Kevin 2013-05-12 03:06:56