Java Scanner findInLine() 方法
示例
在文字行中查詢電子郵件地址
// 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.findInLine("[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]{2,}");
// Show the email if found
if (email != null) {
System.out.println(email);
} else {
System.out.println("No email found");
}
// Close the scanner
myObj.close();
定義和用法
findInLine()
方法會搜尋到掃描器的下一個換行符,查詢由 Pattern
物件或字串提供的正則表示式的第一個匹配項。如果未找到匹配項,則返回 null
。
如果找到匹配項,掃描器將前進到匹配項後的第一個字元。
在我們的 Java 正則表示式教程中瞭解更多關於正則表示式的內容。
語法
以下之一
public String findInLine(Pattern pattern)
public String findInLine(String pattern)
引數值
引數 | 描述 |
---|---|
pattern | 必需。一個字串或 Pattern 物件。指定搜尋中使用的正則表示式。 |
技術詳情
返回 | 一個包含匹配文字的 String ,如果未找到匹配項,則為 null 。 |
---|---|
丟擲 | IllegalStateException - 如果掃描器已被關閉。 |