FR/Documentation/Expressions Regulieres dans Writer

From Apache OpenOffice Wiki
< FR‎ | Documentation
Revision as of 19:31, 8 April 2008 by Sgauti (Talk | contribs)

Jump to: navigation, search


Documentation beingedited.png
Cette page est en cours d'édition


Introduction

En termes simples, les expressions régulières sont une façon plus efficace de trouver et de remplacer du texte (comme avec les caractères génériques). Les expressions régulières peuvent être puissantes et complexes et il est facile pour des utilisateurs inexpérimentés de commettre des erreurs. Nous décrivons l'utilisation des expressions régulières dans OpenOffice.org en essayant d'être le plus clair possible pour le novice, tout en détaillant les aspects qui peuvent provoquer la confusion des utilisateurs plus expérimentés.

Une utilisation typique d'expression régulière est la recherche de texte dans un document Writer ; par exemple pour localiser toutes les occurences de me ou de femme dans le document, vous pouvez alors faire une recherche et utiliser des expressions régulières qui trouveront les deux mots

Les expressions régulières sont très communes dans certains environnements informatique et sont plus connues sous le nom de regex ou regexp. Toutes les regex ne sont pas les mêmes, ainsi lire le manuel les concernant peut se révéler pertinent.

Utilisation des expressions régulières dans OOo

Dans Writer:

  • Dans la boîte de dialogue Édition - Rechercher & remplacer
  • Avec la commande Édition - Modification - Accepter/rejeter (onglet Filtre)


Dans Calc:

  • Dans la boîte de dialogue Édition - Rechercher & remplacer
  • Dans la boîte de dialogue Données - Filtre - Filtre standard
  • Avec les fonctions, telles que SOMME.SI, RECHERCHE


Dans Base:

  • Avec la commande Rechercher un enregistrement

La boîte de dialogue qui apparaît lorsque vous utilisez la commande ci-dessus possède généralement une option d'utilisation des expressions régulières (qui est désactivée par défaut). Par exemple

location of regular expression tick box

Vous devez vérifier le statut des expressions régulières à chaque fois que vous appelez la boîte de dialogue puisque son comportement par défaut est d'être désactivée.

Un exemple simple

Si vous n'avez pas ou peu d'expérience avec les expressions régulières, vous trouverez sans doute plus simple de les étudier à travers Writer qu'à travers Calc.

Dans Writer, appelez la boîte de dialogue Rechercher & remplacer à partir du menu Édition.

Dans la boîte de dialogue, choisissez Autres options et cochez la case Expressions régulières.

Dans la zone Rechercher, saisissez c.s - le point signifie ici 'n'importe quel caractère'.

Cliquer sur le bouton Tout trouver, trouvera tous les mots dont le c est suivi par une autre caractère et suivi par un s, par exemple ces ou 'encas' ou 'incise' ou 'fac similé' (ce dernier exemple est un c suivi par un espace suivi par un s - l'espace est un caractère.

Si vous saisissez xxx dans la zone Remplacer par et cliquez sur le bouton Tout remplacer, cela devient 'xxx', 'enxxx, 'inxxxse, faxxxsimilé'

Ce n'est peut-être pas très utile, mais montre le principe. Nous allons continuer à utiliser la boîte de dialogue Rechercher et remplacer pour expliquer plus en détail.

Le minimum à savoir à propos des expressions régulières

Si vous ne voulez pas savoir exactement comment fonctionnent les expressions régulières, mais voulez seulement obtenir un résultat, vous trouverez utiles les exemples suivants. Saisissez les dans la zone Rechercher et assurez-vous que la case Expressions régulières est cochée.

  • blanc|blanche trouve blanc et blanche
  • b.rde trouve b puis n'importe quel caractère, puis rde - ex barde, briarde, et borde
  • b[ao]nde trouve bande et bonde - [ao] signifie aussi bien a que o
  • changer? renvoie change and changer - le r est facultatif puisqu'il est suivi par un point d'interrogation.
  • s\> trouve le s a la fin d'un mot.
  • \<. trouve la première lettre d'un mot.
  • ^. trouve la première lettre d'un paragraphe.
  • ^$ trouve un paragraphe vide.

Comment sont appliquées les expressions régulières dans OpenOffice.org

Les expressions régulières dans OpenOffice.org divisent le texte à rechercher en portions et examinent chaque portion séparément.

Dans Writer, le texte apparaît séparé en paragraphes. Par exemple x.*z ne correspondra pas à x à la fin d'un paragraphe avec z commençant le paragraphe suivant (x.*z signifie x puis n'importe quels caractères puis z). Les paragraphes semblent être traités séparément (bien que nous parlerons de certains cas spéciaux à la fin de cet how-to).


the scope of regular expressions

De plus Writer considère chaque cellule de tableau et chaque cadre de texte séparément. Les cadres de texte sont examinés après que tout autre texte ou cellules de tableau sur toutes les pages aient été examinés.

Dans la boîte de dialogue Rechercher & remplacer, les expressions régulières doivent être utilisées dans la zone Rechercher. En général, elles ne doivent pas être utilisées dans la zone Remplacer par. Les exceptions sont discutées plus loin.

Caractères littéraux

Si les expressions régulières utilisées contiennent des caractères autres que ceux appelés 'caractères spéciaux' . ^ $ * + ? \ [ ( { | alors ces caractères correspondent littéralement.

Par exemple : bord correspondra à bord, 'rebord et 'déborder'.

OpenOffice.org vous permet de choisir si vous devez respecter les caractères en 'MAJUSCULE' ou en 'miniscule' dans la rechercher. Si vous cochez la case 'Respecter la casse' dans la boîte de dialogue Rechercher & remplacer, alors bord ne correspondra pas à Bord ou REBORD ; si vous décochez cette case, alors la casse est ignorée et les deux écritures seront trouvées.

Les caractères spéciaux

Les caractères spéciaux sont . ^ $ * + ? \ [ ( { |

Ils ont une signification particulière dans une expression régulière, comme nous allons le décrire.

Si vous souhaitez rechercher un de ces caractères littéralement, placez un backslash '\' avant celui-ci.


Par exemple : pour trouver $100 utilisez \$100 - le \$ est pris pour le caractère $ .

Caractère seul correspondant au .  ?

Le caractère spécial '.' correspond à n'importe quel caractère seul (excepté sur les nouvelles lignes).


Par exemple : c.s correspond à 'ces' and 'encas' et 'inciser' et 'fac similé'


Le caractère spécial point d'interrogation '?' signfie 'correspond à zéro ou à un des caractères précédents' - ou 'correspond au caractère précédent s'il est trouvé'.


Par exemple : lie?n correspond à 'lin' et 'lien' - 'a?' signifie 'correspond à un seul s'il y en a un'.

Les caractères spéciaux peuvent être utilisés en combinaisons avec d'autres. Un point suivi d'un point d'interrogation signifie 'correspond à zéro ou l'un des caractères seuls'.


Par exemple : star.?ing correspond à 'staring', 'starring', 'starting', et 'starling', mais pas 'startling'

Répéter une correspondance + * {m,n}

Le caractère spécial '+' signifie 'correspond à un ou plus des caractères précédents'.

Par exemple : ce+s correspond à 'ces' et 'cees' et 'ceeeees' - e+ signifie correspond à un ou plus e's.


Le caractère spécial étoile '*' signifie 'correspond à zéro ou à plus des caractères précédents'.


Par exemple : lie*n corresond à 'lin' et 'lien' et 'lieeeen' - 'a*' signifie correspond à zéro ou plus de a's .


Une utilisation courante de '*' est après le caractère point. - ie '.*' qui signifie 'n'importe lequel ou pas de caractère'.

Par exemple : lie.*n correspond a 'lien' et à 'lieXn' et à lieYYYYn mais pas à - 'lin' ou 'liXn'.

Utilisez l'étoile '*' avec précautions ; elle va récupérer tout ce qu'elle peut :

Par exemple : 'l.*n' correspond à lien mais dans Writer, si la paragraphe est actuellement 'Une vendeuse lui a montré le lien marron', la correspondance trouvée est lui a montré le lien marron - à savoir, le premier 'l' et le dernier 'n' possible. Les expressions régulières sont gourmandes par nature.

Vous devez spécifier combien de fois la correspondance doit être répétée, avec des accolades { }. Par exemple a{1,4}rgh! correspondra à argh!, aargh!, aaargh! et aaaargh! - en d'autres termes entre 1 et 4 a puis rgh!.

Notez également que a{3}rgh! correspondra exactement à 3 a, ie aaargh! et a{2,}rgh! (avec une virgule) correspondra à au moins 2 a, par exemple aargh! et aaaaaaaargh!.

Correspondance de position ^ $ \< \>

Le caractère spécial accent circonflexe '^' signifie 'correspond au début du texte'.

Le caractère spécial '$' signifie 'correspond à la fin du texte'.

Souvenez-vous que les expressions régulières d'OpenOffice.org divisent le texte à rechercher - chaque paragraphe de Writer est examiné de façon séparée.

Par exemple : ^cas correspond à 'cas' au début d'un paragraphe (Cas à étudier...).

Par exemple : cas$ correspond à 'cas' à la fin d'un paragraphe (Étude de cas).

Par exemple : ^cas$ correspond à une cellule de tableau ne contenant que 'cas'.

De plus, un retour à la ligne forcé (saisi par Maj+Entrée) est considéré comme le début ou la fin d'un texte et autorisera la correspondance avec ^ et $.

Le caractère spécial backslash '\' donne une signification spéciale à la paire de caractères '\<' et '\>', c'est à dire 'correspond au début d'un mot' et 'correspond à la fin d'un mot.

Par exemple : \<cas correspond à 'cas' au début d'un mot (il prend le casier près de la porte).

Par exemple : cas\> correspond à 'cas' à la fin d'un mot (il prend un encas pour le déjeuner).

Le test utilisé pour définir le début ou la fin d'un mot semble être que le caractère précédent ou suivant est un espace, un caractère de soulignage (_), une tabulation, une nouvelle ligne, une marque de paragraphe ou n'importe quel caractère non alphanumérique.

Par exemple : \<cas correspond à 'personne@cassis.com'

Par exemple : cas\> correspond à 'Je lui ai dit "N'oublie pas ton encas"'

Correspondances alternatives | [...]

Le caractère spécial pipe '|' permet de rechercher la correspondance de l'expression '|' de chaque côté.

Par exemple : rouge|bleu correspond à 'rouge' et 'bleu'

Malheureusement, parfois, les expressions régulières séparées par un caractère pipe ne sont pas évaluées en fonction de la séquence. C'est le sujet de l'issue issue 84828

Par exemple : ^rouge|bleu correspond à des paragraphes commençant par ^'rouge' et n'importe quelle occurrence de ^'bleu', mais ^bleu|^rouge correspond de façon incorrecte aux occurrences de ^'bleu', et oublie de correspondre aux paragraphes commençant par ^'rouge'.

Le crochet ouvert [ est un caractère spécial. Les caractères entourés de crochets sont traités comme des alternatives - n'importe lequel d'entre eux peut correspondre. Vous pouvez également inclure des plages de caractères comme a-z ou 0-9 plutôt que saisir abcdefghijklmnopqrstuvwxyz ou 0123456789.

Par exemple : c[ea]s correspond à 'ces' et 'cas' mais pas à 'cos' .

Par exemple : [m-p]ue correspond à 'mue' et 'nue' et 'oue' et 'pue'

Par exemple : [hm-p]ue correspond à 'hue' et 'mue' et 'nue' et 'oue' et 'pue'

Les caractères spéciaux utilisés à travers les crochets n'ont pas la même signification spéciale. Les seuls caractères qui ont une signification spéciale sont ], -, ^ et \ et leur signification est :


  • ] - un crochet fermant termine l'ensemble de correspondance alternative [abcdef]
  • - - un tiret indique une plage de caractères comme nous l'avons vu dans [0-9]
  • ^ - si l'accent circonflexe est le premier caractère dans les crochets, il interdit la recherche sur ces caractères. Par exemple [^a-dxyz] correspond à n'importe quel caractères sauf abcdxyz.
  • \ - le backslash est utilisé pour permettre à ], -, ^ et \ d'être utlisés littéralement entre les crochets. Par exemple \]] correspond à un crochet fermant littéral, ainsi [[\]a] correspondra à un crochet ouvrant [, un crochet fermant ] ou un a. \\ correspond à un backslash littéral.

Pour insister : Ceci est la signification de ces caractères à l'intérieur des crochets, et n'importe quel autre caractère est traité littéralement. Par exemple [\t ] correspondra à un backslash \, un 't' ou à un espace - pas à une tabulation ou à un espace.

POSIX bracket expressions [:alpha:] [:digit:] etc..

There is much confusion in the OpenOffice.org community about these. The Help itself is also far from clear.

There are a number of 'POSIX bracket expressions' (sometimes called 'POSIX character classes') available in OpenOffice.org regular expressions, of the form [:classname:] which allow a match with any of the characters in that class. For instance [:digit:] stands for any of the digits 0123456789.

These (by definition) may only appear inside the square brackets of an alternative match - so a valid syntax would be [abc[:digit:]], which should match a, b, c, or any digit 0-9. A correct syntax to match just any one digit would be [[:digit:]].

Unfortunately this does not work as it should! The correct syntax does not work at all, but currently an incorrect syntax ([:digit:]) will actually match a digit, as long as it is outside the square brackets of an alternative match. (Obviously this is unsatisfactory, and is the subject of issue 64368).

The POSIX bracket expressions available are listed below. Note that the exact definition of each depends on locale - for example in a different language other characters may be considered 'alphabetic letters' in [:alpha:]. The meanings given here apply generally to English-speaking locales (and do not take into account any Unicode issues).

[:digit:] 
stands for any of the digits 0123456789. This is equivalent to 0-9.
[:space:] 
should stand for any whitespace character, including tab; however as currently implemented it stands simply for a space character. Note that the Help is currently misleading here. (This is the subject of issue 41706).
[:print:] 
should stand for any printable character; however as currently implemented it does not match the single quote nor the double quote characters ‘ ’ “ ” (and some others such as « »). It matches space, but does not match tab (this latter is expected/defined behaviour). (This is the subject of issue 83290).
[:cntrl:] 
stands for a control character. As far as a user is concerned, OpenOffice.org documents have very few control characters; tab and hard_line_break are both matched, but paragraph_mark is not.
[:alpha:] 
stands for a letter (including a letter with an accent). For example in the phrase (often used in English, and here given with accents as in the original language) 'déjà vu' all 6 letters will match.
[:alnum:] 
stands for a character that satisfies either [:alpha:] or [:digit:]
[:lower:] 
stands for a lowercase letter (including a letter with an accent). The case matching does not work unless the Match case box is ticked; if this box is not ticked this expression is equivalent to [:alpha:].
[:upper:] 
stands for an uppercase letter (including a letter with an accent). The case matching does not work unless the Match case box is ticked; if this box is not ticked this expression is equivalent to [:alpha:].


There seems to be little consistency in any implementation of POSIX bracket expressions (OOo or elsewhere). One approach is simply to use straightforward character classes - so instead of [[:digit:]] you use [0-9] for example.


Grouping (...) and backreferences \x

Round brackets ( ) may be used to group terms.


For example: red(den)? will find 'red' and 'redden'; here (den)? means 'one or zero of den'.

For example: (blue|black)bird will find both 'bluebird' and 'blackbird'.


Each group enclosed in round brackets is also defined as a reference, and can be referred to later in the same expression using a 'backreference'. The backreference '\1' stands for 'whatever matched in the first round brackets'; '\2' stands for 'whatever matched in the second round brackets'; and so on.


For example: (blue|black) \1bird will find both 'blue bluebird' and 'black blackbird', because '\1' stands for either blue or black, whichever we found. Therefore 'black bluebird' does not match.


Please note that backreferences may only be used in the 'Search for' box at present, not in the 'Replace with' box.


The target for implementation of backreferences in the 'Replace with' box is OOo2.4. A workaround until then is to use Find all, then immediately use Find/Replace again in the current selection only. This may (or may not) allow you to do what you want.

(technical note: issue 15666 covers this. Backreferences in the 'Replace with' box will be $1, $2, $3 etc. This is consistent with perl syntax, and more particularly with the ICU regex engine, which may at some time replace the existing OOo regex engine, thus resolving many issues.)


Tabs, newlines, paragraphs \t \n $

The character pair '\t' has special meaning - it stands for a tab character.


For example: \tred will match a tab character followed by the word 'red'.


In Writer a newline may be entered by pressing Shift-Enter. A newline character is thereby inserted into the text, and the following text starts on a new line. This is not the same as a new paragraph; click View-Non printing characters to see the difference.


The OOo regular expression behaviour when matching paragraph marks and newline characters is 'unusual'. This is partly because regular expressions in other software usually deal with ordinary plain text, whereas OOo regular expressions divide the text at paragraph marks. For whatever reason, this is what you can do:


  • \n will match a newline (Shift-Enter) if it is entered in the Search box. In this context it is simply treated like a character, and can be replaced by say a space, or nothing. The regular expression red\n will match red followed by a newline character - and if replaced simply by say blue the newline will also be replaced. The regular expression red$ will match 'red' when it is followed by a newline. In this case, replacing with 'blue' will only replace 'red' - and will leave the newline intact.
  • red\ngreen will match 'red' followed by a newline followed by 'green'; replacing with say 'brown' will remove the newline. However neither red.green nor red.*green will match here - the dot . does not match newline.
  • $ on its own will match a paragraph mark - and can be replaced by say a 'space', or indeed nothing, in order to merge two paragraphs together. Note that red$ will match 'red' at the end of a paragraph, and if you replace it with say a space, you simply get a space where 'red' was - and the paragraphs are unaffected - the paragraph mark is not replaced. It may help to regard $ on its own as a special syntax, unique to OOo.
  • ^$ will match an empty paragraph, which can be replaced by say nothing, in order to remove the empty paragraph. Note that ^red$ matches a paragraph with only 'red' in it - replacing this with nothing leaves an empty paragraph - the paragraph marks at either end are not replaced. It may help to regard ^$ on its own as a special syntax, unique to OOo. Unfortunately, because OOo has taken over this syntax, it seems you cannot use ^$ to find empty cells in a table (nor empty Calc cells).
  • If you wish to replace every newline with a paragraph mark, firstly you will search for \n with Find All to select the newlines. Then in the Replace box you enter \n, which in the Replace box stands for a paragraph mark; then choose Replace. This is somewhat bizarre, but at least now you know. Note that \r is interpreted as a literal 'r', not a carriage return.


Hexadecimal codes \xXXXX

The character sequence ' \x then a 4 digit hexadecimal number ' stands for the character with that code.

For example: \x002A stands for the star character '*'.

Hexadecimal codes can be seen on the 'Insert-Special Character' dialog.


The 'Replace with' box \t \n &

Users are sometimes confused with what can be done using the 'Replace with' box in a Find & Replace dialog.

In general, regular expressions do not work in the 'Replace with' box. The characters you type replace the found text literally.

The three constructs that do work are:

  • \t inserts a tab, replacing the text found.
  • \n inserts a paragraph mark, replacing the text found. This may be unexpected, because \n in the 'Search for' box means 'newline'! In some operating systems it is possible to use unicode input to directly type a newline character (U+000A) in the 'Replace with' box, providing a workaround, but this is not universal.
  • & inserts the entire text found.

For example if you searched for bird|berry, you would would find either 'bird' or 'berry'; now to replace with black& would give you either 'blackbird' or 'blackberry'.

Please note that backreferences or sub-matches such as \1, \2 are not available in the 'Replace with' box yet - see note under the Grouping and backreferences section above.

Troubleshooting OOo regular expressions

If you are new to regular expressions, please realise that they can be tricky - if you are not getting the results you expect, you might need to check that you understand well enough. Try to keep regular expressions as simple and unambitious as possible.


Here are some further points of interest with OOo regular expressions:

  • If you find an unexpected behaviour, please check in the relevant section in this HowTo - many of the behaviour issues have been documented here.
  • Regular expressions are 'greedy' - that is they will match as much text as they can. Consider using curly and square brackets; for example [^ ]{1,5}\> matches 1 to 5 non-space characters at the end of a word.
  • Please be careful when using the Replace All button. There are a few rare occasions when this will give unexpected results. For example to remove the first character of every paragraph you might 'Search for' ^. and 'Replace with' nothing; clicking 'Replace All' now will wipe out *all* your text, instead of just the first character of each paragraph. Issue 82473 discusses this. The workaround is to 'Find All', then 'Replace'; perhaps the safest way is not to use the 'Replace All' button at all with regular expressions.


Tips and Tricks

Here are some examples that may be useful:

\<([^ ]+)[ ]+\1

finds duplicate words separated by spaces (note that there is a space before each ])

\<[1-9][0-9]*\>

finds decimal numbers

\<0[0-7]*\>

finds octal (base 8) numbers

\<0x[A-Fa-f0-9]+\>

finds hexadecimal (base 16) numbers

[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-z]{2,6}

finds most email addresses (there is no perfect regular expression - this is a practical solution)

External Links

Personal tools
In other languages