2016-11-07 56 views
0

場景:java模式使用

Pattern whitespace = Pattern.compile("^\\s"); 
matcher = whitespace.matcher(" WhiteSpace"); 

Pattern whitespace2 = Pattern.compile("^\\s\\s"); 
matcher2 = whitespace2.matcher(" WhiteSpace"); 

我想在一行的開頭拿到空格。我想要獲得確切數量的空格匹配器。我的字符串是" WhiteSpace"
問題是matchermatcher2在這個字符串上工作。

我想要的東西是:
一個模式只能得到1個空格,但這個模式對於2個空格字符串不應該工作 。在下面的情況下,matcher.find()matcher2.find()都是正確的。但matcher.find()應該是false,matcher2.find()應該是true。

我想匹配爲" WhiteSpace"是真實的,虛假的" WhiteSpace"(兩個空格)
我想matcher2爲真:" WhiteSpace"


我想要做的事情是;
我有一個字符串" two whitespaces"
下面兩個if語句都是真的。 matcher應該是錯誤的。 matcher2應該是正確的。

Pattern whitespace = Pattern.compile("^\\s"); 
matcher = whitespace.matcher(" two whitespaces"); 

Pattern whitespace2 = Pattern.compile("^\\s\\s"); 
matcher2 = whitespace2.matcher(" two whitespaces"); 

if(matcher.find()==true){ 
    //XXXXXXXXXXX 
} else if(matcher2.find()==true){ 
    //YYYYYYYYYYY 
} 

回答

1

如果你想確保一個空格後有沒有其他的空白,但你實際上並不希望包括第二個字符將測試其在比賽(如果不管它是空白或不)您可以使用negative lookahead機制(?!..)

所以模式可在線路的開始匹配只有空白,如果沒有其他的空格它可能看起來像

Pattern whitespace = Pattern.compile("^\\s(?!\\s)"); 

這可以適用於任何數量的空格之後

Pattern whitespace = Pattern.compile("^\\s{3}(?!\\s)"); 
+0

謝謝Pshemo。它的工作:) – ivbtar

1

這裏的模式可能會過度殺傷*。使用Character.isWhitespace並得到一個簡單的代碼:

String in = " your input here"; 
int wsPrefix=0; 
for (; wsPrefix < in.length() && Character.isWhitespace(in.charAt(wsPrefix)) ; 
     wsPrefix++) {} 
System.out.println("wsPrefix = " + wsPrefix); 

*對於有人說:

「有些人,當遇到一個問題,想 「我知道,我將使用正則表達式。 「現在他們有兩個問題 - Jaimie Zawinski, 1997