Java virknes spēles ()

Java virknes atbilstības () metode pārbauda, ​​vai virkne atbilst norādītajai regulārajai izteiksmei.

Virknes matches()metodes sintakse ir šāda:

 string.matches(String regex)

Šeit virkne ir Stringklases objekts .

atbilst () parametri

matches()Metode ņem vienu parametru.

  • regex - regulāra izteiksme

valueOf () Return Value

  • atgriež vērtību true, ja regex izteiksme atbilst virknei
  • atgriež false, ja regex neatbilst virknei

1. piemērs: Java atbilst ()

 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 ) )

Šeit "^a… s$"ir regex, kas nozīmē 5 burtu virkni, kas sākas ar a un beidzas ar s.

2. piemērs: pārbaudiet skaitļus

 // 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 ) )

Šeit "^(0-9)+$"ir regex, kas nozīmē tikai ciparus.

Lai uzzinātu vairāk par regex, apmeklējiet Java Regex.

Interesanti raksti...