Java Language Regular Expressions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

A regular expression is a special sequence of characters that helps in matching or finding other strings or sets of strings, using a specialized syntax held in a pattern. Java has support for regular expression usage through the java.util.regex package. This topic is to introduce and help developers understand more with examples on how Regular Expressions must be used in Java.

Syntax

  • Pattern patternName = Pattern.compile(regex);
  • Matcher matcherName = patternName.matcher(textToSearch);
  • matcherName.matches() //Returns true if the textToSearch exactly matches the regex
  • matcherName.find() //Searches through textToSearch for first instance of a substring matching the regex. Subsequent calls will search the remainder of the String.
  • matcherName.group(groupNum) //Returns the substring inside of a capturing group
  • matcherName.group(groupName) //Returns the substring inside of a named capturing group (Java 7+)

Remarks

Imports

You will need to add the following imports before you can use Regex:

import java.util.regex.Matcher
import java.util.regex.Pattern

Pitfalls

In java, a backslash is escaped with a double backslash, so a backslash in the regex string should be inputted as a double backslash. If you need to escape a double backslash (to match a single backslash with the regex, you need to input it as a quadruple backslash.

Important Symbols Explained

CharacterDescription
*Match the preceding character or subexpression 0 or more times
+Match the preceding character or subexpression 1 or more times
?Match the preceding character or subexpression 0 or 1 times

Further reading

The regex topic contains more information about regular expressions.



Got any Java Language Question?