文檔上說\s表示空白字元 斷行符號算不算空白字元呢
用實際例子測試了一下,不同的環境結果各不相同
測試檔案內容
test.txt
PH
P and JA
VA
$text=file_get_contents('test.txt');#print $text;preg_match("/PH\sP/s",$text,$match);print_r($match);preg_match("/JA\sVA/s",$text,$match);print_r($match);
php匹配出來為空白
Pattern php = Pattern.compile("PH\\sP",Pattern.DOTALL);Pattern java = Pattern.compile("JA\\sVA",Pattern.DOTALL); BufferedReader in = new BufferedReader(new FileReader("test.txt")); StringBuffer sb=new StringBuffer (); String s; while ((s = in.readLine()) != null) { sb.append(s); }Matcher m = php.matcher(sb);while(m.find()) { System.out.println(m.group());} m = java.matcher(sb);while(m.find()) { System.out.println(m.group());}
java都能匹配出來
回複內容:
文檔上說\s表示空白字元 斷行符號算不算空白字元呢
用實際例子測試了一下,不同的環境結果各不相同
測試檔案內容
test.txt
PH
P and JA
VA
$text=file_get_contents('test.txt');#print $text;preg_match("/PH\sP/s",$text,$match);print_r($match);preg_match("/JA\sVA/s",$text,$match);print_r($match);
php匹配出來為空白
Pattern php = Pattern.compile("PH\\sP",Pattern.DOTALL);Pattern java = Pattern.compile("JA\\sVA",Pattern.DOTALL); BufferedReader in = new BufferedReader(new FileReader("test.txt")); StringBuffer sb=new StringBuffer (); String s; while ((s = in.readLine()) != null) { sb.append(s); }Matcher m = php.matcher(sb);while(m.find()) { System.out.println(m.group());} m = java.matcher(sb);while(m.find()) { System.out.println(m.group());}
java都能匹配出來
斷行符號是/r/n,不是空白,要在/s模式下就包括了,preg_match('/lalla /s',$youString)
,s 模式中的圓點元字元(.)匹配所有的字元,包括分行符號
如果設定了s這個修飾符,模式中的"點號"元字元匹配所有字元,包含分行符號。如果沒有這個 修飾符,點號不匹配分行符號。這個修飾符等同於 perl 中的/s修飾符。 一個取反字元類比如 1 總是匹配分行符號,而不依賴於s這個修飾符的設定。
- a