Maison  >  Article  >  Java  >  Expressions régulières en Java

Expressions régulières en Java

WBOY
WBOYoriginal
2024-08-30 15:33:26272parcourir

En Java, Regex ou expression régulière est une interface de programme d'application qui permet de définir un modèle pour rechercher, manipuler et modifier des chaînes. Les expressions régulières Java sont largement utilisées dans la validation des mots de passe et des e-mails. Ces expressions sont fournies par le package java.util.regex et se composent de 1 interface et de 3 classes.

Les trois classes sont :

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

  • Motif : Aide à définir des modèles.
  • Matcher : L'utilisation de modèles aide à effectuer des opérations de correspondance.
  • PatternSyntaxException : Aide à indiquer une erreur de syntaxe.

Java Regex possède une interface appelée MatchResultInterface qui aide à déterminer le résultat de l'opération de correspondance de l'expression régulière.

Syntaxe des expressions régulières en Java

Voyons comment écrire une expression régulière en Java à l'aide d'un programme.

Code :

//Java program to demonstrate regular expressions
import java.util.regex.*;
public class RegExamples {
public static void main(String args[]){
String A = " Happiness is " + " within yourself";
String B = ".*within.*";
// checks whether the string A contains the word 'within' and stores the result in matchcheck
boolean matchcheck = Pattern.matches(B, A);
//prints the result
System.out.println("Is there any string 'within' in the text ? \n " + matchcheck);
}   }

Sortie :

Expressions régulières en Java

Méthodes couramment utilisées dans les expressions régulières

Il existe 3 méthodes couramment utilisées dans les expressions régulières.

1. Méthodes d'indexation

Les méthodes d'index offrent des valeurs d'index qui aident à montrer précisément où la correspondance a été trouvée dans la chaîne donnée en entrée.

Method Description
start() The previous match’s start index is returned.
start(int group) Given the group’s previous match operation, the subsequence is captured and returned.
end() The offset after matching the last character is returned.
End(int group) Given the group’s previous match operation, subsequence is captured and offset after matching its last character returned.
Méthode

Description

start() L'index de début de la correspondance précédente est renvoyé. début (groupe int) Compte tenu de l'opération de correspondance précédente du groupe, la sous-séquence est capturée et renvoyée. end() Le décalage après la correspondance avec le dernier caractère est renvoyé. Fin(int groupe) Compte tenu de l'opération de correspondance précédente du groupe, la sous-séquence est capturée et décalée après avoir fait correspondre son dernier caractère renvoyé. 2. Méthodes d'étude
Method Description
lookingAt() Match the sequence given as input against the pattern from the beginning of the region.
find() Finds the next subsequence of the sequence given as input against the pattern from the beginning of the region.
find(int start) Resets the matcher and then finds the next subsequence of the sequence given as input against the specified index pattern.
matches() Matches content against the pattern.

Les méthodes d'étude vérifient la chaîne donnée en entrée et une valeur booléenne est renvoyée, indiquant si le modèle est trouvé ou non.

Méthode

Method Description
appendReplacement(StringBuffer s, String replacement) A non-terminal append and replacement step will be implemented.
appendTail(StringBuffer s) A terminal append and replacement step will be implemented.
replaceAll(String replacement) Replace all subsequence of the sequence given as input that matches against the pattern with a replacement string.
quoteReplacement(String s) A literal replacement string will be returned for the mentioned string.
replaceFirst(String replacement) Replace the first subsequence of the sequence given as input that matches the pattern with a replacement string.
Description lookingAt() Faites correspondre la séquence donnée en entrée avec le motif du début de la région. trouver() Trouver la sous-séquence suivante de la séquence donnée en entrée par rapport au modèle du début de la région. trouver(int début) Réinitialise le matcher, puis recherche la sous-séquence suivante de la séquence donnée en entrée par rapport au modèle d'index spécifié. matches() Faire correspondre le contenu au modèle. 3. Méthodes de remplacement Méthodes utilisées pour remplacer du texte dans une chaîne. Méthode Description appendReplacement(StringBuffer s, remplacement de chaîne) Une étape d'ajout et de remplacement non terminal sera implémentée. appendTail(StringBuffers) Une étape d'ajout et de remplacement de terminal sera mise en œuvre. replaceAll(Remplacement de chaîne) Remplacez toutes les sous-séquences de la séquence donnée en entrée qui correspondent au modèle par une chaîne de remplacement. quoteReplacement(String s) Une chaîne de remplacement littérale sera renvoyée pour la chaîne mentionnée. replaceFirst(Remplacement de chaîne) Remplacez la première sous-séquence de la séquence donnée en entrée qui correspond au modèle par une chaîne de remplacement.

How to Define Regular Expression in Java?

There are several ways in which a regular expression can be defined.

1. Literals

Suppose a string “hai” has to be searched in the text “hai”.

It can be done using syntax.

Pattern.matches("hai", "hai")

2. Character Classes

It matches every single character in the text given as input against multiple permitted characters in the character class.

The following are the various class constructs.

Character Class Explanation
[pqr] Matches the text if it contains either p, q or r, and it should be only once.
[^pqr] ^ denotes the negation, and due to that, here, single character except for p, q, or r are taken.
[a-zA-Z] a to z and A to Z are considered.
[a-d[p-s]] a to d, or p to s.
[a-dm-p] Union of both ranges.
[a-z&&[pqr]] a to z and (p, q or r).
[a-z&&[^pq]] a to z and also, p, q are not considered.
[ad-z] Performs the subtraction.
[a-z&&[^m-p]] a to z and not m to p.

3. Metacharacters

Metacharacters act like shortcodes in the regular expression.

The following are some of the metacharacters commonly used.

Regular Expression Explanation
\d Any digit from 0 to 9. It can be written as [0-9] as well.
\D Any non-digit from 0 to 9. It can be written as [^0-9] as well.
\s Whitespace character or [\t\n\x0B\f\r].
\S Non whitespace character or [^\s].
\w Word character or [a-zA-Z_0-9].
\W Non-word character or [^\w].
\b Word boundary.
\B Non-word boundary.

4. Quantifiers

Quantifiers mention the count of occurrence of each character to match against the string.

Regular Expression Explanation
a? It occurs once or not at all.
A* A occurs 0 or more times.
A+ A occurs 1 or more times.
A{n} A occurs exactly n times.
A{n,} A occurs n or more than that.
A{n,m} A occurs at least n times, but it should not be more than m times.

How to Create Regular Expression in Java?

Now, let us see a java program with the above-mentioned regular expressions.

Code:

//Java program to demonstrate regular expressions
import java.util.regex.*;
public class RegExamples {
public static void main(String args[]){
String str="hai";
// Returns true if string 1 matches string 2
System.out.println("Returns true if 'hai' matches 'Hai' :"+
Pattern.matches(str, "Hai")); //False
//Returns true if Hai or hai matches parameter 2
System.out.println("Returns true if 'Hai' or 'hai' matches 'Hai' : "+
Pattern.matches("[Hh]ai", "Hai")); //True
// Returns true if the string matches exactly "ann" or "Ann" or "jak" or "Jak"
System.out.println("Returns true if the string matches exactly 'ann' or 'Ann' or 'jak' or 'Jak' with 'Ann' : "+
Pattern.matches("[aA]nn|[jJ]ak", "Ann"));//True
//returns true if the string contains "with" at any place in the string
System.out.println("returns true if the string contains 'with' in the string 'within' : " +
Pattern.matches(".*with.*", "within"));//True
// returns true if the '9448anna' does not have number in the beginning
System.out.println( "returns true if the '9448anna' does not have number in the beginning : "+
Pattern.matches("^[^\\d].*", "9448anna")); //False
System.out.println("returns true if the '9448anna' does not have number in the beginning : " +
Pattern.matches("^[^\\d].*", "anna9448")); //True
}
}

Output:

Expressions régulières en Java

Conclusion – Regular Expressions in Java

Java Regular Expressions are widely used for real-time applications such as password and email verification. These expressions are APIs that define patterns and offer searching, editing, and several other operations in the string.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:Fonction de hachage en JavaArticle suivant:Fonction de hachage en Java