Correspondências de string Java ()

O método Match () da String Java verifica se a string corresponde à expressão regular fornecida ou não.

A sintaxe do matches()método string é:

 string.matches(String regex)

Aqui, string é um objeto da Stringclasse.

Match () Parâmetros

O matches()método usa um único parâmetro.

  • regex - uma expressão regular

valueOf () Valor de retorno

  • retorna verdadeiro se o regex corresponder à string
  • retorna falso se o regex não corresponder à string

Exemplo 1: correspondência de Java ()

 class Main ( public static void main(String() args) ( // a regex pattern for // five letter string that starts with 'a' and end with 's' String regex = "^a… s$"; System.out.println("abs".matches(regex)); // false System.out.println("alias".matches(regex)); // true System.out.println("an abacus".matches(regex)); // false System.out.println("abyss".matches(regex)); // true ) )

Aqui "^a… s$"está uma regex, o que significa string de 5 letras que começa com a e termina com s.

Exemplo 2: verificar se há números

 // check whether a string contains only numbers class Main ( public static void main(String() args) ( // a search pattern for only numbers String regex = "^(0-9)+$"; System.out.println("123a".matches(regex)); // false System.out.println("98416".matches(regex)); // true System.out.println("98 41".matches(regex)); // false ) )

Aqui "^(0-9)+$"está uma regex, o que significa apenas dígitos.

Para saber mais sobre regex, visite Java Regex.

Artigos interessantes...