Regex Pattern Matching in JAVA – String Functions startsWith(),endsWith(),contains()



To identify particular pattern of regular expressions in Strings is achieved in JAVA by using the API java.util.regex. This API consists of two main java classes such as Matcher and Pattern classes. Also we can even use String Functions to identify the particular pattern of regular expressions in the String class.

Pattern Class

A regular expression specified as a String is passed into an instance of this class.
The output is used to create a Matcher object that can match the character sequences against the regular
expression.

Static methods available in the Pattern Class as follows:

  • pattern()
  • split()
  • matcher()
  • compile()
  • matches()

Matcher Class

This java class helps to matches the character sequences by interpreting the pattern.

Static Matcher Methods in the API:

  • start()
  • end()
  • group()

Identify the List of Strings Starts with a particular letter

Output of the Program:

Result:: false
Result:: false
Result:: false
Result:: true
Start index: 0 End index: 1 Group value::t


String Functions to identify the Regular Expressions:

  • startsWith(String prefix)
  • endsWith(String suffix)
  • contains(CharSequence s)

Identify the List of Strings Starts with a particular letter using String Functions

Output of the Program:

String starts with a particular character:::total-qa
String starts with a particular character:::tutorialpoint
String ends with a particular character:::guru99
String contains with a particular character:::total-qa
String contains with a particular character:::javatpoint
String contains with a particular character:::tutorialpoint


Conclusion:

Using the String functions and java.util.regex API, identification of the pattern in the given Strings is possible using the above examples.

Leave a Reply

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