How to use Regular Expressions in Java – String Class Tutorial
We can use Regular Expressions on String class in Java. It can be applied on the following Methods.
- public boolean matches(String regex) – Tells whether or not this string matches the given regular expression.
- public String[] split(String regex,int limit) – Splits this string around matches of the given regular expression.
- public String[] split(String regex) – Splits this string around matches of the given regular expression.
- replaceAll(String regex, String replacement) – Replaces each substring of this string that matches the given regular expression with the given replacement.
- replaceFirst(String regex, String replacement) – Replaces the first substring of this string that matches the given regular expression with the given replacement.
Regex in String Class – Tutorial
package com.javaindetail.PatternTutorial;
public class StringRegexTutorial {
public static final String TEXT_FOR_REGEX = "This is a technical blog about java. javaindetail.com is a technical blog. Explore everything in detail";
public static void main(String[] args) {
System.out.println(TEXT_FOR_REGEX.matches("\w.*"));
// splitting the string with spaces
String[] splitString = (TEXT_FOR_REGEX.split("\s+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
// replace all whitespace with tabs
System.out.println(TEXT_FOR_REGEX.replaceAll("\s+", "t"));
}
}
Output
true
16
This
is
a
technical
blog
about
java.
javaindetail.com
is
a
technical
blog.
Explore
everything
in
detail
This is a technical blog about java. javaindetail.com is a technical blog. Explore everything in detail
Enjoy Reading This Article?
Here are some more articles you might like to read next: