Java String matches example

In this post, we are going to see String’s matches method.

String’s matches method

String matches method is used to check whether the string is matched with the given regular expression.In normal terms, we can pass various regular expressions to check if the specified string matches with that regular expression.If the matches get successful return true otherwise false.

String matches method throws PatternSyntaxException if the given regular expression is not valid.

Syntax:

How to use matches method:

String matches method use regular expression.so, two widely used regular expression meta characters are dot (.) and astrick (). (.) which matches any character and () which matches any number of times.Make regular expression according to your pattern you want to match.
Below given example perform the following task:
• Checks if string contains any numeric digit or not ex: [0-9]
• Checks if string contains any character or not ex: [A-Za-z].
• Checks string contains given word or not ex: (john)
For all these, we can create  regular expressions and check it with String’s matches method.

String matches example:

Output:

Hello i am john,id is 1 and my seat number is 88
===================
Number matching example
===================
pattern: .*[1-9].* matches => true
pattern: .*(100).* matches => false
pattern: .*(88).* matches => true
===================
Character matching example
===================
pattern: .*[A-Za-z].* matches => true
pattern: .*[A].* matches => false
pattern: .*[i].* matches => true
===================
Word and String matching example
===================
pattern: .*(john).* matches => true
pattern: .*(Hello i am john).* matches => true
pattern: .*(JOHN).*matches => falseHello i am johnMehra
pattern: .*(Mehra).* matches => true
pattern: john matches => false

That’s all about Java String’s matches method.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *