Java String match () meetod kontrollib, kas string vastab antud regulaaravaldisele või mitte.
Stringi matches()
meetodi süntaks on:
string.matches(String regex)
Siin on string String
klassi objekt .
vasted () Parameetrid
matches()
Meetod võtab ühe parameetri.
- regex - regulaarne väljend
valueOf () Return Value
- tagastab tõene, kui regex vastab stringile
- tagastab vale, kui regex ei vasta stringile
Näide 1: Java vastab ()
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 ) )
Siin "^a… s$"
on regex, mis tähendab viietähelist stringi, mis algab tähega ja lõpeb tähega s
.
Näide 2: kontrollige numbreid
// 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 ) )
Siin "^(0-9)+$"
on regex, mis tähendab ainult numbreid.
Regexi kohta lisateabe saamiseks külastage Java Regexi.