English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Método Matcher lookingAt() com exemplo em Java

A classe java.util.regex.Matcher representa o motor de operações de correspondência. Esta classe não possui construtor, e pode ser criada usando o método matchs() da classe java.util.regex.Pattern/Obter um objeto deste tipo.

Matcherda classelookingAt()Este método começa a verificar a correspondência do texto de entrada com o padrão a partir do início da região. Se houver correspondência, o método retorna true, caso contrário, retorna false. Diferente do método matches(), este método não requer que toda a região correspondente possa retornar true.

exemplo1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(*)\\d+)(*)";
      String input = "Este é um exemplo de texto" 1234, com números entre eles. "
         + "\n Este é a segunda linha do texto"
         + "\n Este é a terceira linha do texto"
      //Criando um objeto padrão
      Pattern pattern = Pattern.compile(regex);
      //Criando um objeto Matcher
      Matcher matcher = pattern.matcher(input);
      //verificando correspondência
      if(matcher.lookingAt()) {
         System.out.println("Correspondência encontrada");
      } else {
         System.out.println("Nenhuma correspondência encontrada");
      }
   }
}

Output Result

encontrou correspondência

exemplo2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LookingAtExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter String1: ");
      String input1 = sc.nextLine();
      System.out.println("Enter String2: ");
      String input2 = sc.nextLine();
      System.out.println("Enter String3: ");
      String input3 = sc.nextLine();
      String input = input1+"\n"+input2+"\n"+input3;
      System.out.println(input);
      //Regular expression to match a word that contain digits
      String regex = ".*\\d+.*";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //verifying whether match occurred
      boolean bool = matcher.lookingAt();
      if(bool) {
         System.out.println("Given input contains digit");
      } else {
         System.out.println("Given input does not contain any digit");
      }
   }
}

Output Result

Enter String1:
sample text2
Enter String2:
data
Enter String3:
sample
sample text2
data
sample
Given input contains digit