這段代碼爲什麼會拋出InputMismatchException?爲什麼「你好*世界」不匹配「你好世界」?
Scanner scanner = new Scanner("hello world");
System.out.println(scanner.next("hello\\s*world"));
相同的正則表達式中http://regexpal.com/匹配(與\ S代替\\ S的)
這段代碼爲什麼會拋出InputMismatchException?爲什麼「你好*世界」不匹配「你好世界」?
Scanner scanner = new Scanner("hello world");
System.out.println(scanner.next("hello\\s*world"));
相同的正則表達式中http://regexpal.com/匹配(與\ S代替\\ S的)
掃描儀,而不是一個Matcher,有建於串的標記化,默認的分隔符是空白。所以你的「你好世界」在比賽運行之前變成「你好」「世界」。這將是一場比賽,如果你在掃描之前改變了分隔符不是字符串的東西,如:
Scanner scanner = new Scanner("hello world");
scanner.useDelimiter(":");
System.out.println(scanner.next("hello\\s*world"));
但它似乎是真正爲你的情況,你應該只使用Matcher
。
這是使用掃描儀「爲目的」的例子:
Scanner scanner = new Scanner("hello,world,goodnight,moon");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next("\\w*"));
}
輸出將
hello
world
goodnight
moon
如果字符串是hello:world then ?!你不應該對你輸入的內容做出假設:S – 2011-06-10 17:21:09
這對於說明Navin爲什麼他的代碼不起作用有什麼關係?我說:「如果出現下面的情況,這將是一個匹配:」不是「如果出現以下情況,這將是嚴格正確的代碼,適用於生產用途:」輸入顯然被認爲是「hello world」;) – Affe 2011-06-10 17:24:40
您可以設置一個空的分隔符而不是a: – 2011-06-10 17:25:15
掃描儀具有的\\s+
默認定界符,如果你想只匹配hello\\s*world
,只需撥打scanner.useDelimiter("hello\\s*world"))
,然後只需scanner.next();
替代方案勞改,你可以調用scanner.useDelimiter('any (escaped) char that would not occur in your text ')
和使用scanner.next("hello\\s*world"))
作爲一個側面說明,如果你希望它有至少1個空間,你想用一個+
而不是*
這不起作用。 「」的分隔符標記爲高級字體。 – Affe 2011-06-10 17:37:33
我已經編輯過:)你需要使用一些當然不在你的輸入中的字符。請注意,某些字符是特殊的正則表達式字符,您需要將它們轉義才能使用它們。我總是使用一個安全的字符是# – 2011-06-10 17:39:11
掃描儀的構造函數的可選模式,用於將輸入序列分割爲令牌。默認情況下,這是一個空白模式。
如果下一個標記與給定的模式匹配,則它將返回下一個標記。換句話說,您傳遞給#next的模式默認情況下可能不包含空格。
您可以調用#useDelimiter爲您的用例配置掃描儀。
掃描儀的默認分隔符是空格,所以掃描儀看到兩個元素你好和世界。並且hello \ s + world與hello不匹配,因此引發NoSuchElement異常。
這些投入工作:
"C:\Program Files\Java\jdk1.6.0_21\bin\java" RegexTest hello\s+world "hello world"
'hello world' does match 'hello\s+world'
下面的代碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
if (args.length > 0) {
Pattern pattern = Pattern.compile(args[0]);
for (int i = 1; i < args.length; ++i) {
Matcher matcher = pattern.matcher(args[i]);
System.out.println("'" + args[i] + "' does " + (matcher.matches() ? "" : "not ") + "match '" + args[0] +"'");
}
}
}
}
http://regexpal.com/測試JavaScript的正則表達式,而不是Java正則表達式。您可以嘗試使用http://www.fileformat.info/tool/regex.htm來測試Java正則表達式。 – Marcelo 2011-06-10 17:16:05
@Marcelo我最喜歡的在線Java正則表達式測試程序:http://www.regexplanet.com/simple/ – 2011-06-23 18:50:59
@Matt謝謝,我爲它下一次我需要一個書籤。 – Marcelo 2011-06-23 19:50:58