Learn Regular Expressions in Java

Regular expressions in Java

Leer Gereelde uitdrukkings in Java,,en,java.util.regex,,ro,API bestaan ​​uit verskeie klasse waarvan elkeen 'n spesifieke verantwoordelikheid het,,en,patroon word gebruik om patrone te definieer terwyl die,,en,java.util.regex.Matcher,,sv,word gebruik vir ooreenstemmende bewerkings gebaseer op die patrone gedefinieer deur die,,en,java.util.regex.Pattern,,de,Dit gaan net oor die gebruik van die toepaslike klas vir die doel,,en,Ons sal kyk hoe gereelde uitdrukkings in Java-toepassings gebruik kan word,,en,Weet jy,,en,Hoekom het ons gereelde uitdrukking nodig,,en,Gereelde uitdrukkings kan uiters nuttig wees, veral in groot sagteware-ontwikkelingsprojekte met lang kodelyne,,en,In sulke projekte,,en,sagteware ontwikkelaars moet verskeie dinge doen soos om herbruikbare blokke kodes te skep,,en,refactoring of skoonmaak kodes en kommentaar vir kodes,,en,Stel jou voor dat jy dit handmatig oor 'n groot kodebasis doen,,en

Oorsig:

Java provides regular expression packages that are useful for software developers and testers alike. Java regular expressions are varied, versatile and allow developers to define string patterns that can be used to search, edit or manipulate text. The java.util.regex API comprises multiple classes each of which has a specific responsibility. For example, the java.util.regex pattern is used for defining patterns while the java.util.regex.Matcher is used for matching operations based on the patterns defined by the java.util.regex.Pattern klas. It is just about using the appropriate class for the purpose.

In this article, we will check how regular expressions can be used in Java applications.








Do you know – Steps to work with Java Persistence API?

Why we need regular expression?

Regular expressions can be immensely useful especially in large software development projects with long lines of code. In such projects, software developers need to do several things such as creating reusable blocks of codes; refactoring or cleaning codes and putting comments for codes. Now, imagine doing that manually over a large codebase. Dit sou 'n kolossale vermorsing van tyd en produktiwiteit wees,,en,Dit is waar gereelde uitdrukkings so nuttig is,,en,Sagteware ontwikkelaars of selfs die toetsers kan spesifieke reëlmatige uitdrukkings vir spesifieke doeleindes definieer en die gewone uitdrukking hergebruik,,en,as die ontwikkelaar wil soek vir 'n term "hulpbron" oor die kode basis sonder dat die soektog hoegenaamd hoofletters is,,en,dan kan die ontwikkelaar 'n gereelde uitdrukking ooreenkomstig die volgende definieer,,en,String inhoud =,,en,Dit is 'n hulpbronproduk,,en,String patternString =,,en,hulpbron.,,en,Patroonpatroon = Patroon.samestelling,,en,patternString,,en,Herbruikbaarheid en doeltreffendheid is twee van die belangrikste voordele van 'n gereelde uitdrukking,,en,Die groot ding is dat verskeie gereelde uitdrukkings gedefinieer kan word afhangende van die doel,,en,Komponente van Java gereelde uitdrukking pakket,,en. This is where regular expressions are so helpful. Software developers or even the testers can define specific regular expressions for specific purposes and just reuse the regular expression. For example, if the developer wants to search for a term “resource” across the code base without the search being case-sensitive, then the developer could define a regular expression accordingly like the following:

String content = “This is a resource product”;

String patternString = “.*reSoUrCe.”;

Pattern pattern=Pattern.compile (patternString, Pattern.CASE_INSENSITIVE);

Re-usability and efficiency are two of the main advantages of having a regular expression. The great thing is that multiple regular expressions can be defined depending on the purpose.

Must Read – Steps to work with Java generics?








Components of Java regular expression package

Voordat ons begin om gereelde uitdrukkings in Java te skryf,,en,Ons moet 'n duidelike begrip hê van die beskikbare komponente in die java.util.regex-pakket,,en,Daar is hoofsaaklik drie klasse in die pakket beskikbaar,,en,Kom ons kyk wat hulle eintlik doen,,en,Patroon klas,,en,Gereelde uitdrukkings word algemeen voorgestel as 'n reeks karakters / simbole / spesiale karakters ens,,en,Die basiese proses is om dit 'n voorwerp te maak voordat dit bruikbaar is,,en,Sodra die gewone uitdrukking saamgestel is,,en,dit word 'n patroonvoorwerp,,en,Patroon klas het geen openbare bouer nie,,en,Dit het 'n openbare statiese leegmaakmetode genoem,,en,'saam te stel,,en,Gereelde uitdrukking word as 'n argument aan hierdie metode oorgedra en die terugkeervoorwerp is 'n Patroonobjek,,en,Soos ons in ons voorbeeld aansoek gebruik het,,en,Patroon toets_pattern = Patroon.samestelling,,en,s ,,en, we should have a clear understanding of the components available in the java.util.regex package.

There are mainly three classes available in the package. Let’s have a look at what they actually do.

Pattern class: Regular expressions are generally represented as a sequence of characters/symbols/special characters etc. So, the basic process is to make it an object before it is usable. Once the regular expression is compiled, it becomes a pattern object. Pattern class does not have any public constructor. It has a public static void method called ‘compile’. Regular expression is passed to this method as an argument and the return object is a Pattern object. As we have used in our sample application.

Pattern test_pattern = Pattern.compile (“\\s ”, Pattern.CASE_INSENSITIVE);

Also read – JSON data and Java – How it works?

Matcher klas,,en,sodra die patroonvoorwerp geskep is,,en,ons moet 'n meganisme hê om die insetstring met die patroon te vergelyk,,en,Hier kom die rol van die Matcher-klas,,en,Dit dien as 'n regex-enjin om die insette en die patroon te pas,,en,Dit het geen openbare bouer nie,,en,Die matcher-metode van Patroon-voorwerp word eerder gebruik om die insette te neem en 'n Matcher-voorwerp terug te gee,,en,Na hierdie die wedstryde,,en,metode van die Matcher klas word gebruik om die werklike resultaat te kry,,en,dit gee 'n Boole-waarde terug wat aandui of die resultaat waar is,,en,ooreenstem,,en,of vals,,en,nie ooreenstem nie,,en,Die volgende voorbeeld toon die implementering,,en,Toets Regex komponente in Java,,en,pakket demo.techalpine.com,,en,invoer java.util.regex. *,,ro,openbare klas RegExComponents,,en,Patroonvoorwerp skep,,en,Patroon tst_pattern = Pattern.compile,,en,smekinge.,,uz,Skep 'n Matcher-voorwerp,,en: Now, once the Pattern object is created, we need to have some mechanism to compare the input string with the Pattern. Here comes the role of Matcher class, it acts as a regex engine to match the input and the Pattern. It does not have any public constructor, rather the matcher method of Pattern object is used to take the input and return a Matcher object. After this the ‘matches’ method of Matcher class is used to get the actual result, it returns a Boolean value indicating whether the result is true (matched) or false (not matched).








Following example shows the implementation.

Listing 1: Testing Regex components in Java

[kode]

package demo.techalpine.com;

import java.util.regex.*;

public class RegExComponents {

openbare statiese nietig hoof(String[] argumente) {

//Creating Pattern object

Pattern tst_pattern = Pattern.compile(“.duoni.”);

//Creating Matcher object

Vergelyk tst_matcher = tst_pattern.matcher,,sv,Toets insetstring,,en,Nagaan,,en,as toevoerstring ooreenstem met die patroon,,en,tst_matcher.matches,,lb,Stel nou die klas op en hardloop,,en,PatternSyntaxException klas,,en,Dit is die uitsonderingsklas wat gebruik word om enige sintaksfout op te spoor,,en,Nou is jou omgewing ingestel om gereelde uitdrukkings in Java te skryf,,en,Kom ons probeer 'n voorbeeld aansoek,,en,In hierdie afdeling sal ons 'n voorbeeld aansoek skryf om gereelde uitdrukking te toets,,en,Volgende skermskoot toon die projekstruktuur vir die aansoek,,en,In hierdie voorbeeld sal ons 'n eenvoudige tou met wit spasies hê,,en,Hierdie string sal die inset vir die wedstryd wedden,,en,Nou is die doel om die wit spasies te verwyder en te vervang met '**' string,,en,Ons sal 'n Patroon klas en 'n Matcher klas skep,,en(“TechAlpine”);

//Testing input string

System.out.println(“Checking…if input string matches with the pattern – “+tst_matcher.matches());

}

}

[/kode]

Now compile and run the class.

PatternSyntaxException class: This is the exception class used for detecting any syntax error.

Environment setup:

To configure the environment following are the four steps to be followed

  • Download JDK from the following link and set the class path

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Now your environment is set to write regular expressions in Java. In the next section we will create one sample application.

You will like to read – Creating RESTful web service in Java

Let’s try a sample application:

In this section we will write a sample application for testing regular expression. Following screen shot shows the project structure for the application.

In this example we will have a simple string with white spaces. This string will bet the input to the matcher. Now the objective is to remove the white spaces and replace it with ‘**’ string.

We will create a Pattern class and a Matcher class. Daarna sal die insetstring geslaag word om na die patroon te kyk,,en,Ons sal ook die indekse van die wit spasies in die tou wys,,en,Volg die projekstruktuur in die Eclipse-omgewing,,en,Sodra die program geskryf is,,en,stel dit op en hardloop dit,,en,openbare klas RegDemo,,en,Skep voorbeeldstring vir toetsing,,en,openbare statiese finale string SAMPLE_STRING =,,en,Kom ons kyk gereelde uitdrukking in Java,,en,Wedstryde test_matcher = test_pattern.matcher,,sv,SAMPLE_STRING,,en,Laat ons die wedstryd druk,,en,Druk van die wedstryd,,en,test_matcher ,,no,Kom ons kyk wat ooreenstem met indekse,,en,Drukindekse,,en,test_matcher.find,,da,Begin indeks,,en,test_matcher.start,,en,Sluitingsindeks,,en,test_matcher.end,,da,Stel nou die patroon saam,,en,Patroon vervang_pattern = Patroon.samestelling,,en,Pas die patroon met die steekproef string,,en,Wedstryde second_matcher = replace_pattern.matcher,,sv,Druk oorspronklike string,,en,Vervang nou die spasies met,,en. We will also display the indexes of the white spaces in the string.

Follow the project structure in the Eclipse environment. Once the program is written, compile and run it.


Listing 2: monster aansoek

[kode]

package demo.techalpine.com;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegDemo {

// Creating sample string for testing

public static final String SAMPLE_STRING = “Let us check regular expression in Java”;

openbare statiese nietig hoof(String[] argumente) {

Pattern test_pattern = Pattern.compile(“\\s ”, Pattern.CASE_INSENSITIVE);

Matcher test_matcher = test_pattern.matcher(SAMPLE_STRING);

//Let us print the matcher

System.out.println(“Printing the matcher:- “+ test_matcher “\n”);

//Let us check matching indexes

System.out.println(“Printing indexes:- “+”\n”);

terwyl (test_matcher.find()) {

System.out.print(“Starting index: ” + test_matcher.start());

System.out.print(“Closing index: ” + test_matcher.end() + “\n”);

}

//Now compiles the pattern

Pattern replace_pattern = Pattern.compile(“\\s ”);

//Matching the pattern with the sample string

Matcher second_matcher = replace_pattern.matcher(SAMPLE_STRING);

//Printing original string

System.out.println(“\n”+”Printing original string:- “+”\n”);

System.out.println(SAMPLE_STRING);

//Now replace the spaces with ** character

System.out.println(“\n”+”Druk die gewysigde string,,en,second_matcher.replaceAll,,en,Stel nou die aansoek op en voer dit uit,,en,In hierdie artikel het ons verskillende komponente van Java gereelde uitdrukkingspakket bespreek,,en,Ons het ook nagegaan hoe dit werk en waarom dit belangrik is,,en,Gereelde uitdrukkings word gebruik in verskillende scenario's soos wagwoord validering,,en,e-pos adres validering ens,,en,Die basiese idee is om 'n patroon volgens die vereiste te skep en dan die insette te bevestig,,en,Dit is wat gereelde uitdrukkings eintlik doen,,en,Dit verminder die ontwikkelingstyd en skep herbruikbare komponente,,en,Dit is dus baie nuttig om gereelde uitdrukkings te leer en dit dan volgens behoefte te skep,,en,Alle Java-artikels,,en,Gereelde uitdrukkings,,en,techalpine.com/learn-regular-expressions-in-java,,en:- “+”\n”);

System.out.println(second_matcher.replaceAll(“**”));

}

}

[/kode]

Now compile and run the application.

Read – Learn Log4j – Logging API for Java








Gevolgtrekking: In this article we have discussed different components of Java regular expression package. We have also checked how it works and why it is important. Regular expressions are used in different scenarios like password validation, email address validation etc. The basic idea is to create a pattern as per the requirement and then validate the input. This is what regular expressions actually do. It reduces the development time and creates reusable components. So it is very helpful to learn regular expressions and then create it as per need.

Must Read- All Java articles


 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share