DEV Community


Regex in Java

tawfikyasser profile image Tawfik Yasser ・2 min read


Our use of Java increases with time, and because of this, we must know more needs that help us with the code and give the code less of our products, and examples of these needs
The Regular Expression or Regex
And we will talk about it in Java

The Regex is a set of specific letters that we write in order to search for a specific pattern in the input, times when it becomes a letter or two and other times to be very complicated pattern.

In general, Regex has many expressions, and when you know them, you can apply them in any language, depending on the syntax you write in.

Examples of Regex:

\ d
This means that you are rotating any number from 0 to 9
\ w
It means that you are running a burn, whether it is an upper case, lower case, or a number
\ s
This means space
This is used if you want to roll a letter or number in a specific range

Example: [a-n] This means that you only rotate the lower case letter from a to n

Ok, if I want, for example, the user, the input, enters a number from 4 to 9, but it is necessary to enter a number at least, and it is possible to enter a lot, but it is necessary to enter at least one number in the form of this + [9-4]
Thus, the regex does not have many needs that you can search for and use in the code instead of what we do.

As an example in Java:

If I want to check the input, it has a number in the first from 1 to 5, then any letter from m to r, then any number from 2 to 4

Scanner scanner = new Scanner (;
String input = scanner.nextLine ();
Pattern pattern = Pattern.compile ("[1-5] [m-r] [2-4]");
Matcher matcher = pattern.matcher (input);
boolean found = matcher.find ();
if (found) {
System.out.println ("Pattern found:" + input);
} else {
System.out.println ("Pattern not found.");
Enter fullscreen mode Exit fullscreen mode
It is just a beginning in Regex

Discussion (0)

Forem Open with the Forem app