當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.util.Scanner.findWithinHorizon()用法及代碼示例


描述

這個java.util.Scanner.findWithinHorizon(Pattern pattern,int horizon)方法 嘗試查找指定模式的下一次出現。此方法搜索輸入直到指定的搜索範圍,忽略分隔符。如果找到了模式,掃描器會前進到匹配的輸入並返回與模式匹配的字符串。如果沒有檢測到這樣的模式,則返回空值並且掃描儀的位置保持不變。此方法可能會阻止等待與模式匹配的輸入。掃描儀永遠不會搜索超過其當前位置的水平碼點。請注意,匹配可能會被地平線剪掉;也就是說,如果視界更大,則任意匹配結果可能會有所不同。

聲明

以下是聲明java.util.Scanner.findWithinHorizon()方法

public String findWithinHorizon(Pattern pattern,int horizon)

參數

pattern- 指定要搜索的模式的字符串

返回值

此方法返回與指定模式匹配的文本。

異常

  • IllegalStateException- 如果此掃描儀已關閉

  • IllegalArgumentException- 如果地平線為負

示例

下麵的例子展示了 java.util.Scanner.findWithinHorizon() 方法的用法。

package com.tutorialspoint;

import java.util.*;
import java.util.regex.Pattern;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // find a pattern of 2 letters before rld, with horizon of 10
      System.out.println("" + scanner.findWithinHorizon(Pattern.compile("..rld"), 10));

      // find a pattern of 2 letters before rld, with horizon of 20
      System.out.println("" + scanner.findWithinHorizon(Pattern.compile("..rld"), 20));

      // print the rest of the string
      System.out.println("" + scanner.nextLine());

      // close the scanner
      scanner.close();
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

null
World
! 3 + 3.0 = 6

相關用法


注:本文由純淨天空篩選整理自 Java.util.Scanner.findWithinHorizon() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。