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 参数为负。 |