How to extract a substring using regex

To extract a substring from a string using a regular expression in Java, you can use the following steps:

  1. Compile the regular expression pattern using the compile() method of the Pattern class:
Pattern pattern = Pattern.compile("regex pattern");
  1. Create a Matcher object from the input string using the matcher() method of the Pattern class:
String input = "input string";
Matcher matcher = pattern.matcher(input);
  1. Use the find() method of the Matcher class to find the first occurrence of the substring that matches the regular expression:
if (matcher.find()) {
  // the substring was found
}
  1. Extract the substring using the group() method of the Matcher class:
String group = matcher.group();

Here's an example of how you can use these steps to extract a substring that consists of the first four characters of an input string:

Pattern pattern = Pattern.compile("^.{4}");
String input = "input string";
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
  String substring = matcher.group();
}

The regular expression "^.{4}" matches any four characters at the beginning of the input string (the ^ character denotes the start of the string). The .{4} part of the pattern matches any four characters (the . character matches any character, and the {4} specifies that the preceding character should be matched four times).