Aide:StringRegExp.txt

De Wiki AutoIt Français
Aller à : navigation, rechercher

Document original V3.3.6.1 :

###Function###
StringRegExp

###Description###
Check if a string fits a given regular expression pattern.

###Syntax###
StringRegExp ( "test", "pattern" [, flag ] [, offset ] ] )


###Parameters###
@@ParamTable@@
test
	The string to check
pattern
	The regular expression to compare.
flag
	[optional] A number to indicate how the function behaves.  See below for details.  The default is 0.
offset
	[optional] The string position to start the match (starts at 1)  The default is 1.
@@End@@
<br>
@@ParamTable@@
<b>Flag</b>
	<b>Values</b>
0
	Returns 1 (matched) or 0 (no match)
1
	Return array of matches.
2
	Return array of matches including the full match (Perl / PHP style).
3
	Return array of global matches.
4
	Return an array of arrays containing global matches including the full match (Perl / PHP style).
@@End@@

###ReturnValue###
<i>Flag = 0 :</i>

@@ReturnTable@@
@Error	Meaning
2 	Bad pattern. @Extended = offset of error in pattern.
@@End@@

<br>
<i>Flag = 1 or 2 :</i>

@@ReturnTable@@
@Error	Meaning
0	Array is valid.  Check @Extended for next offset
1	Array is invalid.  No matches.
2	Bad pattern, array is invalid.  @Extended = offset of error in pattern.
@@End@@

<br>
<i>Flag = 3 or 4 :</i>

@@ReturnTable@@
@Error	Meaning
0	Array is valid.
1	Array is invalid.  No matches.
2	Bad pattern, array is invalid.  @Extended = offset of error in pattern.
@@End@@


###Remarks###
The flag parameter can have one of 5 values (0 through 4).  0 gives a true (1) or false (0) as to whether the pattern was found or not.  1 and 2 find the first match and returns it in an array.  3 and 4 find multiple hits and fills the array with all the matching text.  2 and 4 include the full matching text as the first record, not just the capturing groups, which is all you get with flag 1 and 3.

Regular expression notation is a compact way of specifying a pattern for strings that can be searched.  Regular expressions are character strings in which plain text characters indicate what text should exist in the target string, and a some characters are given special meanings to indicate what variability is allowed in the target string.  AutoIt regular expressions are normally case-sensitive.

Regular expressions are constructed of one or more of the following simple regular expression specifiers.  If the character is not in the following table, then it will match only itself.

Repeating characters (*, +, ?, {...} ) will try to match the largest set possible, which allows the following characters to match as well, unless followed immediately by a question mark; then it will find the smallest pattern that allows the following characters to match as well.

Nested groups are allowed, but keep in mind that all the groups, except non-capturing groups, assign to the returned array, with the outer groups assigning after the inner groups.

Complete description can be found <b><a href="http://www.autoitscript.com/autoit3/pcrepattern.html" target="_blank">here</a></b>

<b>Caution</b>: bad regular expressions can produce a quasi-infinite loop hogging the CPU, and can even cause a crash.

<b><u>Matching Characters</u></b>

@@ParamTable@@
[ ... ]
	Match any character in the set.  e.g. <b>[aeiou]</b> matches any lower-case vowel.  A contiguous set can be defined using a dash between the starting and ending characters.  e.g. <b>[a-z]</b> matches any lower case character.  To include a dash (<b>-</b>) in a set, use it as the first or last character of the set.  To include a closing bracket in a set, use it as the first character of the set.  e.g. <b>[][]</b> will match either [ or ].  Note that special characters <b>do not</b> retain their special meanings inside a set, with the exception of <b>\\</b>,  <b>\^</b>, <b>\-</b>,<b>\[</b> and <b>\]</b> match the escaped character inside a set.
[^ ... ]
	Match any character <b>not</b> in the set.  e.g. <b>[^0-9]</b> matches any non-digit.  To include a caret (<b>^</b>) in a set, put it after the beginning of the set or escape it (\^).
[:class:]
	Match a character in the given class of characters.  Valid classes are: alpha (any alphabetic character), alnum (any alphanumeric character), lower (any lower-case letter), upper (any upper-case letter), digit (any decimal digit 0-9), xdigit (any hexadecimal digit, 0-9, A-F, a-f), space (any whitespace character), blank (only a space or tab), print (any printable character), graph (any printable character except spaces), cntrl (any control character [ascii 127 or <32]) or punct (any punctuation character). So [0-9] is equivalent to [[:digit:]].
[^:class:]
	Match any character <b>not</b> in the class, but only if the first character.
( ... )
	Group. The elements in the group are treated in order and can be repeated together.  e.g. <b>(ab)+</b> will match "ab" or "abab", but not "aba".  A group will also store the text matched for use in back-references and in the array returned by the function, depending on flag value.
(?i)
	Case-insensitivity flag.  This does not operate as a group.  It tells the regular expression engine to do case-insensitive matching from that point on.
(?-i)
	(default) Case-sensitivity flag.  This does not operate as a group.  It tells the regular expression engine to do case-sensitive matching from that point on.
(?: ... )
	Non-capturing group.  Behaves just like a normal group, but does not record the matching characters in the array nor can the matched text be used for back-referencing.
(?i: ... )
	Case-insensitive non-capturing group.  Behaves just like a non-capturing group, but performs case-insensitive matches within the group.
(?-i: ... )
	Case-sensitive non-capturing group.  Behaves just like a non-capturing group, but performs case-sensitive matches within the group.
(?m)
	^ and $ match newlines within data.
(?s)
	. matches anything including newline. (by default "." don't match newline)
(?x)
	Ignore whitespace and # comments.
(?U)
	Invert greediness of quantifiers.
<b>.</b>
	Match any single character (except newline).
|
	Or.  The expression on one side <b>or</b> the other can be matched.
\
	<i>Escape</i> a special character (have it match the actual character) or introduce a special character type (see below).
\\
	Match an actual backslash (\).
\a
	Alarm, that is, the BEL character (chr(7)).
\A
	Match only at beginning of string.
\b
	Matches at a word boundary.
\B
	Matches when not at a word boundary.
\c
	Match a control character, based on the next character.  For example, <b>\cM</b> matches ctrl-M.
\d
	Match any digit (0-9).
\D
	Match any non-digit.
\e
	Match an escape character (chr(27)).
\E
	end case modification.
\f
	Match an formfeed character (chr(12)).
\h
	any horizontal whitespace character.
\H
	any character that is not a horizontal whitespace character.
\n
	Match a linefeed (@LF, chr(10)).
\Q
	quote (disable) pattern metacharacters till \E.
\r
	Match a carriage return (@CR, chr(13)).
\s
	Match any whitespace character: Chr(9) through Chr(13) which are Horizontal Tab, Line Feed, Vertical Tab, Form Feed, and Carriage Return, and the standard space ( Chr(32) ).
\S
	Match any non-whitespace character.
\t
	Match a tab character (chr(9)).
\v
	any vertical whitespace character.
\V
	any character that is not a vertical whitespace character.
\w
	Match any "word" character: a-z, A-Z, 0-9 or underscore (_).
\W
	Match any non-word character.
\###
	Match the ascii character whose code is given or back-reference.  Can be up to 3 octal digits.<br>Match back-reference if found. Match the prior group number given exactly.  For example, <b>([:alpha:])\1</b> would match a double letter.
\x##
	Match the ascii character whose code is given in hexadecimal.  Can be up to 2 digits.
\z
	Match only at end of string.
\Z
	Match only at end of string, or before newline at the end.
@@END@@

<u><b>Repeating Characters</u></b>

@@ParamTable@@
{<i>x</i>}
	Repeat the previous character, set or group exactly <i>x</i> times.
{<i>x</i>,}
	Repeat the previous character, set or group at least <i>x</i> times.
{0,<i>x</i>}
	Repeat the previous character, set or group at most <i>x</i> times.
{<i>x</i>, <i>y</i>}
	Repeat the previous character, set or group between <i>x</i> and <i>y</i> times, inclusive.
*
	Repeat the previous character, set or group 0 or more times.  Equivalent to {0,}
+
	Repeat the previous character, set or group 1 or more times.  Equivalent to {1,}
?
	The previous character, set or group may or may not appear.  Equivalent to {0, 1}
? (after a repeating character)
	Find the smallest match instead of the largest.
@@END@@

<u><b>Character Classes</u></b>

@@ParamTable@@
[:alnum:]
	letters and digits
[:alpha:]
	letters
[:ascii:]
	character codes 0 - 127
[:blank:]
	space or tab only
[:cntrl:]
	control characters
[:digit:]
	decimal digits (same as \d)
[:graph:]
	printing characters, excluding space
[:lower:]
	lower case letters
[:print:]
	printing characters, including space
[:punct:]
	printing characters, excluding letters and digits
[:space:]
	white space (not quite the same as \s, it include VT: chr(11) )
[:upper:]
	upper case letters
[:word:]
	"word" characters (same as \w)
[:xdigit:]
	hexadecimal digits
@@END@@


###Related###
StringInStr, StringRegExpReplace


###Example###
@@IncludeExample@@


Document traduit V3.3.6.1 :

###Function###
StringRegExp

###Description###
Vérifie si une chaîne de caractères correspond à un modèle d'expression régulière.


###Syntax###
StringRegExp ( "test", "pattern" [, flag ] [, offset ] ] )


###Parameters###
@@ParamTable@@
test
	La chaîne à vérifier
pattern
	L'expression régulière à comparer.
flag
	[optionnel] Nombre qui indique comment la fonction se comporte. Voir plus bas pour plus de détails. La valeur par défaut est 0.
offset
	[optionnel] La position dans la chaîne pour commencer la recherche (commence à 1). La valeur par défaut est 1.
@@End@@
<br>
@@ParamTable@@
<b>Flag</b>
	<b>Valeurs</b>
0
	Retourne 1 (trouvé) or 0 (non trouvé)
1
	Retourne un tableau de résultats.
2
	Retourne un tableau de résultats incluant le résultat complet (style Perl / PHP).
3
	Retourne un tableau de résultats globaux.
4
	Retourne un tableau de tableau contenant les résultats globaux incluant le résultat complet (style Perl / PHP).
@@End@@


###ReturnValue###
<i>Flag = 0 :</i>

@@ReturnTable@@
@Error	Signification
2 	Mauvais modèle. @Extended = position de l'erreur dans le modèle.
@@End@@

<br>
<i>Flag = 1 or 2 :</i>

@@ReturnTable@@
@Error	Signification
0	Tableau retourné valide. Voir @Extended pour la position suivante
1	Tableau retourné invalide. Pas de résultats.
2	Mauvais modèle, tableau invalide. @Extended = position de l'erreur dans le modèle.
@@End@@

<br>
<i>Flag = 3 or 4 :</i>

@@ReturnTable@@
@Error	Signification
0	Tableau retourné valide.
1	Tableau retourné invalide. Pas de résultats.
2	Mauvais modèle, tableau invalide. @Extended = position de l'erreur dans le modèle.
@@End@@


###Remarks###
Le paramètre flag peut avoir une des 5 valeurs (0 à 4). 0 retourne vrai (1) ou faux (0) selon si le modèle a été trouvé ou non.1 et 2 trouvent la première correspondance et la retourne dans un tableau. 3 et 4 trouvent les différentes correspondances et remplit le tableau avec tout les résultats. 2 et 4 incluent le texte complet de la correspondance comme le premier résultat et pas seulement les groupes capturés, qui sont tout ce que vous avez avec le flag 1 et 3.

La notation d'expression régulière est une façon compacte de définir un modèle pour des chaînes
recherchées. Les expression régulières sont des chaînes de caractères dans lesquelles le texte clair indique quel texte doit exister dans la chaîne cible, et certains caractères ont une signification particulière qui indique quelle variabilité est permise dans la chaîne cible. Les expressions régulières d'AutoIt sont normalement sensibles à la casse.

Les expressions régulières sont construites à partir d'un ou plusieurs des spécificateurs suivants. Un caractère absent de la table suivante signifiera ce même caractère.

Les caractères de répétition (*, +, ?, {...} ) essayent de correspondre à la plus grande chaîne possible, à moins d'être suivis immédiatement d'un point d'interrogation, ce qui permet aux caractères suivants d'être trouvés; et ensuite le plus petit modèle qui prend en compte les caractères suivants sera trouvé.

Les groupes emboîtés sont permit, mais gardez à l'esprit que tous les groupes, sauf les groupes non capturant, transmettent au tableau retourné, avec les groupes d'assignation extérieurs après les groupes intérieurs.

Voir la description complète <b><a href="http://www.autoitscript.com/autoit3/pcrepattern.html" target="_blank">ici</a></b> (en anglais).

<b>Attention</b>: de mauvaises expressions régulières peuvent entraîner une boucle quasi-infinie mobilisant le processeur, entraînant même un crash.

<b><u>Caractères de correspondance</u></b>

@@ParamTable@@
[ ... ]
	Correspond à tout caractère du groupe. par ex. <b>[aeiou]</b> spécifie n'importe quelle voyelle en minuscule. Un groupe continu peut être définit en utilisant un tiret entre les caractères de début et de fin. Par ex. <b>[a-z]</b> spécifie n'importe quelle lettre minuscule. Pour inclure un tiret (<b>-</b>) dans un groupe, mettez le comme premier ou dernier caractère du groupe. Pour inclure un crochet fermant dans un groupe, mettez le en premier. Par ex. <b>[][]</b> signifie soit [ soit ]. Notez que les caractères spéciaux <b>ne conservent pas</b> leur signification spéciale dans un groupe, à l'exception de <b>\</b>, <b>^</b>, <b>-</b>, <b>[</b> et <b>]</b>. Pour inclure ces caractères dans un groupe, précédez les d'un anti-slash (<b>\</b>).
[^ ... ]
	Correspond à tout caractère <b>absent</b> du groupe. Par ex. <b>[^0-9]</b> indique n'importe quoi sauf un chiffre. Pour inclure un accent circonflexe (<b>^</b>) dans un groupe, placez le après le début ou précédez le d'un anti-slash (\^).
[:class:]
	Correspond à tout caractère dans la classe donnée de caractères. Les classes de caractères sont : alpha (caractères alphabétiques), alnum (caractères alphanumériques), lower (lettres minuscules), upper (lettres majuscules), digit (chiffres décimaux 0-9), xdigit (chiffres hexadécimaux 0-9, A-F, a-f), space (caractères d'espace), blank (seulement espace et tabulation), print (caractères imprimables), graph (caractères imprimables sauf espaces), cntrl (caractères contrôles [ascii 127 ou <32]) et punct (caractères de ponctuation). Donc [0-9] est équivalent à [[:digit:]].
[^:class:]
	Correspond à tout caractère <b>absent</b> de la classe.
( ... )
	Groupe. Les éléments du groupe sont traités dans l'ordre et peuvent être répétés. Par ex. <b>(ab)+</b> indique "ab" ou "abab", mais pas "aba". Un groupe stockera le texte trouvé pour être utilisé en références arrières et dans le tableau retourné par la fonction selon la valeur de l'option.
(?i)
	Option d'insensibilité à la casse. Ceci n'opère pas comme un groupe, il indique au moteur d'expression régulière de faire une recherche insensible à la casse à partir de cet endroit.
(?-i)
	(défaut) Option de sensibilité à la casse. Ceci n'opère pas comme un groupe, il indique au moteur d'expression régulière de faire une recherche sensible à la casse à partir de cet endroit.
(?i ... )
	Groupe insensible à la casse. Se comporte comme un groupe normal, mais fait une recherche insensible à la casse à l'intérieur du groupe.
(?-i ... )
	Groupe sensible à la casse. Se comporte comme un groupe normal, mais fait une recherche sensible à la casse à l'intérieur du groupe. Principalement pour l'utilisation après l'option (?i) ou à l'intérieur d'un groupe insensible à la casse.
(?: ... )
	Groupe non capturant. Se comporte comme un groupe normal, mais n'enregistre pas les caractères trouvés dans le tableau et le texte trouvé ne peut pas être utilisé pour une référence arrière.
(?i: ... )
	Groupe non capturant insensible à la casse. Se comporte comme un groupe non capturant, mais fait une recherche insensible à la casse à l'intérieur du groupe.
(?-i: ... )
	Groupe non capturant sensible à la casse. Se comporte comme un groupe non capturant, mais fait une recherche sensible à la casse à l'intérieur du groupe.
(?m)
	^ et $ indiquent une nouvelle ligne dans les données.
(?s)
	. indique n'importe quoi incluant une nouvelle ligne. (par défaut "." n'indique pas de nouvelle ligne)
(?x)
	Ignore les espaces et les commentaires #.
(?U)
	Inverse la l'avidité des quantificateurs.
<b>.</b>
	Correspond à tout caractère (sauf nouvelle ligne).
|
	Ou. L'expression d'un côté <b>ou</b> de l'autre peuvent être trouvées.
\
	<i>Annule</i> l'effet d'un caractère spécial (pour qu'il indique le vrai caractère) ou introduit un type de caractère spécial (voir ci-dessous).
\\
	Correspond à un vrai anti-slash (\).
\a
	Alarme, c'est-à-dire caractère BEL (Chr(7)).
\A
	Correspond seulement au début de chaîne.
\b
	Correspond à une limite de mot.
\B
	Correspond lorsqu'en dehors de la limite de mot.
\c
	Correspond à un caractère contrôle, basé sur le caractère suivant. Par exemple, <b>\cM</b> correspond à CTRL-M.
\d
	Correspond à tout chiffre (0-9).
\D
	Correspond à tout caractère qui n'est pas un chiffre.
\e
	Correspond au caractère échap (Chr(27)).
\E
	Fin de modification de la casse.
\f
	Correspond au caractère saut de page (Chr(12)).
\h
	Tout espace horizontal.
\H
	Tout caractère qui n'est pas un espace horizontal.
\l
	Prochain caractère en minuscule.
\L
	Prochains caractères en minuscules jusqu'à \E.
\n
	Correspond au saut de ligne (@LF, Chr(10)).
\Q
	Désactive les méta-caractères de modèle jusqu'à \E.
\r
	Correspond au retour chariot (@CR, Chr(13)).
\s
	Correspond à tout caractère d'espace : Chr(9) à Chr(13) (Tabulation horizontale, Saut de ligne, Tabulation verticale, Saut de page et Retour chariot) et l'espace standard (Chr(32)).
\S
	Correspond à tout caractère qui n'est pas un caractère d'espace.
\t
	Correspond à la tabulation (Chr(9)).
\u
	Prochain caractère en majuscule.
\U
	Prochains caractères en majuscules jusqu'à \E.
\v
	Tout espace vertical.
\V
	Tout caractère qui n'est pas un espace vertical.
\w
	Correspond à tout caractère de "mot" : a-z, A-Z, 0-9 ou tiret du bas (_).
\W
	Correspond à tout caractère qui n'est pas un caractère "mot".
\###
	Correspond au caractère ASCII dont le code est donné en référence arrière. Peut contenir jusqu'à 3 chiffres octaux.<br>Correspond à la référence arrière si trouvée. Correspond au préalable au nombre de groupe donné exactement. Par exemple, <b>([:alpha:])\1</b> correspond à une lettre double.
\x##
	Correspond au caractère dont le code est donné en hexadécimal. Peut contenir jusqu'à 2 chiffres.
\z
	Correspond seulement en fin de chaîne.
\Z
	Correspond seulement en fin de chaîne ou en fin de ligne.
@@END@@

<u><b>Caractères de répétition</u></b>

@@ParamTable@@
{<i>x</i>}
	Répète le caractère précédent, défini ou groupe, exactement <i>x</i> fois.
{<i>x</i>,}
	Répète le caractère précédent, défini ou groupe, au moins <i>x</i> fois.
{0,<i>x</i>}
	Répète le caractère précédent, défini ou groupe, au plus <i>x</i> fois.
{<i>x</i>, <i>y</i>}
	Répète le caractère précédent, défini ou groupe, entre <i>x</i> et <i>y</i> fois inclus.
*
	Répète le caractère précédent, défini ou groupe, 0 fois ou plus. Équivalent à {0,}
+
	Répète le caractère précédent, défini ou groupe, 1 fois ou plus. Équivalent à {1,}
?
	Le caractère précédent, défini ou groupe, peu apparaître ou non. Équivalent à {0, 1}
? (après un caractère de répétition)
	Trouve la plus petite chaîne possible au lieu de la plus grande.
@@END@@

<u><b>Classes de Caractère</u></b>

@@ParamTable@@
[:alnum:]
	chiffres et lettres
[:alpha:]
	lettres
[:ascii:]
	caractère de code 0 - 127
[:blank:]
	espace ou tabulation seulement
[:cntrl:]
	caractères contrôles
[:digit:]
	chiffres décimaux (identique à \d)
[:graph:]
	caractères imprimables sauf espaces
[:lower:]
	lettres minuscules
[:print:]
	caractères imprimables, espaces compris
[:punct:]
	caractères imprimables sauf chiffres et lettres
[:space:]
	espace blanc (pas tout à fait comme \s, cela inclut tab. verticale: Chr(11))
[:upper:]
	lettres majuscules
[:word:]
	caractères "mots" (identique à \w)
[:xdigit:]
	chiffres hexadécimaux
@@END@@


###Related###
<a href="StringInStr.htm">StringInStr</a>, <a href="StringRegExpReplace.htm">StringRegExpReplace</a>


###Example###
@@IncludeExample@@


Traducteur : tolf

Contributeurs (pour les modifications avant le Wiki) : Tlem