Java Scanner findWithinHorizon() 方法
示例
在一行文字中查詢電子郵件地址
// Create a scanner object
Scanner myObj = new Scanner("Please send an email to info@example.com for more details.");
// Get the email address with a pattern
String email = myObj.findWithinHorizon("[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]{2,}", 0);
// Show the email if found
if (email != null) {
System.out.println(email);
} else {
System.out.println("No email found");
}
定義和用法
findWithinHorizon()
方法在指定數量的字元中搜索由 Pattern
物件或字串提供的正則表示式的第一個匹配項。如果未找到匹配項,則返回 null
。
要搜尋的字元數由 horizon 引數指定,如果將其設定為零,則它將無限制地繼續搜尋。
如果找到匹配項,掃描器將前進到匹配項之後的第一個字元。
在我們的 Java 正則表示式教程中瞭解更多關於正則表示式的內容。
語法
以下之一
public String findWithinHorizon(Pattern pattern, int horizon)
public String findWithinHorizon(String pattern, int horizon)
引數值
引數 | 描述 |
---|---|
pattern | 必需。字串或 Pattern 物件。指定搜尋中使用的正則表示式。 |
horizon | 必需。指定搜尋距離的限制。如果值為零,則沒有限制。 |
技術詳情
返回 | 一個包含匹配文字的 String ,如果未找到匹配項則為 null 。 |
---|---|
丟擲 |
IllegalStateException - 如果掃描器已被關閉。IllegalArgumentException - 如果 horizon 引數為負。 |