Difference between revisions of "FR/Documentation/Expressions Regulieres dans Writer"

From Apache OpenOffice Wiki
Jump to: navigation, search
(Répéter une correspondance + * {m,n})
(Répéter une correspondance + * {m,n})
Line 118: Line 118:
  
  
''Par exemple :'' <b>lie*n</b> corresond à <b>'lin'</b> and <b>'lien'</b> and <b>'lieeeen'</b> - <b>'a*'</b> signifie correspond à zéro ou plus de <b>a</b>'s .
+
''Par exemple :'' <b>lie*n</b> corresond à <b>'lin'</b> et <b>'lien'</b> et <b>'lieeeen'</b> - <b>'a*'</b> signifie correspond à zéro ou plus de <b>a</b>'s .
  
  
Line 127: Line 127:
 
Utilisez l'étoile <b>'<nowiki>*</nowiki>'</b> avec précautions ; elle va récupérer tout ce qu'elle peut :  
 
Utilisez l'étoile <b>'<nowiki>*</nowiki>'</b> avec précautions ; elle va récupérer tout ce qu'elle peut :  
  
''For example:'' <b>'r.*d'</b> matches <b>'red'</b> but in Writer if your paragraph is actually 'The referee showed him the red card again' the match found is <b>'referee showed him the red card'</b> - that is, the first <b>'r'</b> and the last possible <b>'d'</b>. Regular expressions are greedy by nature.
+
''Par exemple :'' <b>'l.*n'</b> correspond à <b>lien</b> mais dans Writer, si la paragraphe est actuellement 'Une vendeuse lui a montré le lien marron', la correspondance trouvée est <b>lui a montré le lien marron</b> - à savoir, le premier <b>'l'</b> et le dernier <b>'n'</b> 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 <b>{ }</b>. Par exemple
You may specify how many times you wish the match to be repeated, with curly brackets <b>{ }</b>. For example <b>a{1,4}rgh!</b> will match <b>argh!</b>, <b>aargh!</b>, <b>aaargh!</b> and <b>aaaargh!</b> - in other words between 1 and 4 <b>a</b>'s then <b>rgh!</b>.
+
<b>a{1,4}rgh!</b> correspondra à <b>argh!</b>, <b>aargh!</b>, <b>aaargh!</b> et <b>aaaargh!</b> - en d'autres termes entre 1 et 4 <b>a</b> puis <b>rgh!</b>.
 
+
Also note that <b>a{3}rgh!</b> will match precisely 3 <b>a</b>'s, ie <b>aaargh!</b>, and  <b>a{2,}rgh!</b> (with a comma) will match at least 2 <b>a</b>'s, for example <b>aargh!</b> and <b>aaaaaaaargh!</b>.
+
Notez également que <b>a{3}rgh!</b> correspondra exactement à 3 <b>a</b>, ie <b>aaargh!</b> et <b>a{2,}rgh!</b> (avec une virgule) correspondra à au moins 2 <b>a</b>, par exemple <b>aargh!</b> et <b>aaaaaaaargh!</b>.
  
 
== Positional match ^  $  \<  \> ==
 
== Positional match ^  $  \<  \> ==

Revision as of 17:44, 7 April 2008


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!.

Positional match ^ $ \< \>

The circumflex '^' special character means 'match at the beginning of the text'.

The dollar '$' special character means 'match at the end of the text'.


Remember that OpenOffice.org regular expressions divide up the text to be searched - each paragraph in Writer is examined separately.

For example: ^red matches 'red' at the start of a paragraph (red night shepherd's delight).

For example: red$ matches 'red' at the end of a paragraph (he felt himself go red)

For example: ^red$ matches inside a table cell that contains just 'red'


In addition a hard line break (entered by Shift-Enter) is considered the beginning / end of text, and will allow a ^ or $ match.


The backslash '\' special character gives special meaning to the character pairs '\<' and '\>', namely 'match at the beginning of a word', and 'match at the end of a word'


For example: \<red matches red at the beginning of a word (she went redder than he did).

For example: red\> matches red at the end of a word (although neither of them cared much.)


The test used to define the beginning/end of a word seems to be that the previous/next character is a space, underscore (_), tab, newline, paragraph mark or any non-alphanumeric character.

For example: \<red matches 'person@rediton.com'

For example: red\> matches 'I said, "No-one dared" '


Alternative matches | [...]

The pipe character '|' is a special character which allows the expression either side of the '|' to match.


For example: red|blue matches 'red' and 'blue'


Unfortunately, sometimes expressions separated by a pipe are not all evaluated, depending on the sequence. This is the subject of issue 84828


For example: ^red|blue matches paragraphs beginning with 'red' and any occurrence of 'blue', but blue|^red incorrectly matches only any occurrence of 'blue', failing to match paragraphs beginning with 'red'


The open square brackets character [ is a special character. Characters enclosed in square brackets are treated as alternatives - any one of them may match. You can also include ranges of characters, such as a-z or 0-9, rather than typing in abcdefghijklmnopqrstuvwxyz or 0123456789


For example: r[eo]d matches 'red' and 'rod' but not 'rid'

For example: [m-p]ut matches 'mut' and 'nut' and 'out' and 'put'

For example: [hm-p]ut matches 'hut' and 'mut' and 'nut' and 'out' and 'put'


Special characters within alternative match square brackets do not have the same special meanings. The only characters which do have special meanings are ], -, ^ and \, and the meanings are:

  • ] - a closing square bracket ends the alternative match set [abcdef]
  • - - a hyphen indicates a range of characters, as we've seen, eg [0-9]
  • ^ - if the caret is the first character in the square brackets, it negates the search. For example [^a-dxyz] matches any character except abcdxyz.
  • \ - the backslash is used to allow ], -, ^ and \ to be used literally in square brackets. For example, \] stands for a literal closing square bracket, so [[\]a] will match an opening square bracket [, a closing square bracket ] or an a. \\ stands for a literal backslash.

Just to re-emphasise: these are the meanings of these characters inside square brackets, and any other characters are treated literally. For example [\t ] will match a backslash \, a 't' or a space - not a tab or a space.

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