summaryrefslogtreecommitdiffstats
path: root/doc/man/man3/tqregexp.3qt
blob: da9121c2510abe7a171d3a828a750473f5060fd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
'\" t
.TH QRegExp 3qt "2 February 2007" "Trolltech AS" \" -*- nroff -*-
.\" Copyright 1992-2007 Trolltech ASA.  All rights reserved.  See the
.\" license file included in the distribution for a complete license
.\" statement.
.\"
.ad l
.nh
.SH NAME
QRegExp \- Pattern matching using regular expressions
.SH SYNOPSIS
All the functions in this class are reentrant when TQt is built with thread support.</p>
.PP
\fC#include <ntqregexp.h>\fR
.PP
.SS "Public Members"
.in +1c
.ti -1c
.BI "enum \fBCaretMode\fR { CaretAtZero, CaretAtOffset, CaretWontMatch }"
.br
.ti -1c
.BI "\fBQRegExp\fR ()"
.br
.ti -1c
.BI "\fBQRegExp\fR ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE )"
.br
.ti -1c
.BI "\fBQRegExp\fR ( const QRegExp & rx )"
.br
.ti -1c
.BI "\fB~QRegExp\fR ()"
.br
.ti -1c
.BI "QRegExp & \fBoperator=\fR ( const QRegExp & rx )"
.br
.ti -1c
.BI "bool \fBoperator==\fR ( const QRegExp & rx ) const"
.br
.ti -1c
.BI "bool \fBoperator!=\fR ( const QRegExp & rx ) const"
.br
.ti -1c
.BI "bool \fBisEmpty\fR () const"
.br
.ti -1c
.BI "bool \fBisValid\fR () const"
.br
.ti -1c
.BI "QString \fBpattern\fR () const"
.br
.ti -1c
.BI "void \fBsetPattern\fR ( const QString & pattern )"
.br
.ti -1c
.BI "bool \fBcaseSensitive\fR () const"
.br
.ti -1c
.BI "void \fBsetCaseSensitive\fR ( bool sensitive )"
.br
.ti -1c
.BI "bool \fBwildcard\fR () const"
.br
.ti -1c
.BI "void \fBsetWildcard\fR ( bool wildcard )"
.br
.ti -1c
.BI "bool \fBminimal\fR () const"
.br
.ti -1c
.BI "void \fBsetMinimal\fR ( bool minimal )"
.br
.ti -1c
.BI "bool \fBexactMatch\fR ( const QString & str ) const"
.br
.ti -1c
.BI "int match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const  \fI(obsolete)\fR"
.br
.ti -1c
.BI "int \fBsearch\fR ( const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero ) const"
.br
.ti -1c
.BI "int \fBsearchRev\fR ( const QString & str, int offset = -1, CaretMode caretMode = CaretAtZero ) const"
.br
.ti -1c
.BI "int \fBmatchedLength\fR () const"
.br
.ti -1c
.BI "int \fBnumCaptures\fR () const"
.br
.ti -1c
.BI "QStringList \fBcapturedTexts\fR ()"
.br
.ti -1c
.BI "QString \fBcap\fR ( int nth = 0 )"
.br
.ti -1c
.BI "int \fBpos\fR ( int nth = 0 )"
.br
.ti -1c
.BI "QString \fBerrorString\fR ()"
.br
.in -1c
.SS "Static Public Members"
.in +1c
.ti -1c
.BI "QString \fBescape\fR ( const QString & str )"
.br
.in -1c
.SH DESCRIPTION
The QRegExp class provides pattern matching using regular expressions.
.PP

.PP
Regular expressions, or "regexps", provide a way to find patterns within text. This is useful in many contexts, for example:
.PP
<center>.nf
.TS
l - l. Validation A regexp can be used to check whether a piece of text meets some criteria, e.g. is an integer or contains no whitespace. Searching Regexps provide a much more powerful means of searching text than simple string matching does. For example we can create a regexp which says "find one of the words 'mail', 'letter' or 'correspondence' but not any of the words 'email', 'mailman' 'mailer', 'letterbox' etc." Search and Replace A regexp can be used to replace a pattern with a piece of text, for example replace all occurrences of '&' with '&amp;' except where the '&' is already followed by 'amp;'. String Splitting
.TE
.fi
</center>
.PP
We present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation itself. QRegExp is modeled on Perl's regexp language, and also fully supports Unicode. QRegExp can also be used in the weaker 'wildcard' (globbing) mode which works in a similar way to command shells. A good text on regexps is \fIMastering Regular Expressions: Powerful Techniques for Perl and Other Tools\fR by Jeffrey E. Friedl, ISBN 1565922573.
.PP
Experienced regexp users may prefer to skip the introduction and go directly to the relevant information.
.PP
In case of multi-threaded programming, note that QRegExp depends on QThreadStorage internally. For that reason, QRegExp should only be used with threads started with QThread, i.e. not with threads started with platform-specific APIs.
.PP

.TP
Introduction
.TP
Characters and Abbreviations for Sets of Characters
.TP
Sets of Characters
.TP
Quantifiers
.TP
Capturing Text
.TP
Assertions
.TP
Wildcard Matching (globbing)
.TP
Notes for Perl Users
.TP
 Code Examples

.SH "Introduction"
Regexps are built up from expressions, quantifiers, and assertions. The simplest form of expression is simply a character, e.g. \fBx\fR or \fB5\fR. An expression can also be a set of characters. For example, \fB[ABCD]\fR, will match an \fBA\fR or a \fBB\fR or a \fBC\fR or a \fBD\fR. As a shorthand we could write this as \fB[A-D]\fR. If we want to match any of the captital letters in the English alphabet we can write \fB[A-Z]\fR. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. \fBx{1,1}\fR means match an \fBx\fR which occurs at least once and at most once. We'll look at assertions and more complex expressions later.
.PP
Note that in general regexps cannot be used to check for balanced brackets or tags. For example if you want to match an opening html \fC<b>\fR and its closing \fC</b>\fR you can only use a regexp if you know that these tags are not nested; the html fragment, \fC<b>bold <b>bolder</b></b>\fR will not match as expected. If you know the maximum level of nesting it is possible to create a regexp that will match correctly, but for an unknown level of nesting, regexps will fail.
.PP
We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with \fB[0-9]{1,1}\fR which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes \fB[0-9]{1,2}\fR meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits \fIwithin\fR a string. To ensure that we match against the whole string we must use the anchor assertions. We need \fB^\fR (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need \fB$\fR (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is \fB^[0-9]{1,2}$\fR. Note that assertions, such as \fB^\fR and \fB$\fR, do not match any characters.
.PP
If you've seen regexps elsewhere they may have looked different from the ones above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. \fB[0-9]\fR can be replaced with the symbol \fB\\d\fR. The quantifier to match exactly one occurrence, \fB{1,1}\fR, can be replaced with the expression itself. This means that \fBx{1,1}\fR is exactly the same as \fBx\fR alone. So our 0 to 99 matcher could be written \fB^\\d{1,2}$\fR. Another way of writing it would be \fB^\\d\\d{0,1}$\fR, i.e. from the start of the string match a digit followed by zero or one digits. In practice most people would write it \fB^\\d\\d?$\fR. The \fB?\fR is a shorthand for the quantifier \fB{0,1}\fR, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp \fB^\\d\\d?$\fR means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string".
.PP
Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, \fBm{1,1}a{1,1}i{1,1}l{1,1}\fR, but since each expression itself is automatically quantified by \fB{1,1}\fR we can simply write this as \fBmail\fR; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for \fIalternation\fR, so our regexp now becomes \fBmail|letter|correspondence\fR which means match 'mail' \fIor\fR 'letter' \fIor\fR 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parentheses, \fB(mail|letter|correspondence)\fR. Parentheses have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to capture. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time \fB\\b\fR "word boundary": \fB\\b(mail|letter|correspondence)\\b\fR. This regexp means "match a word boundary followed by the expression in parentheses followed by another word boundary". The \fB\\b\fR assertion matches at a \fIposition\fR in the regexp not a \fIcharacter\fR in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string.
.PP
For our third example we want to replace ampersands with the HTML entity '&amp;'. The regexp to match is simple: \fB&\fR, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: \fB&(?!amp;)\fR. The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must \fInot\fR follow the expression that preceeds it.
.PP
Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are \fB&#92;b(Eric|Eirik)&#92;b\fR and \fB&#92;bEi?ri[ck]&#92;b\fR. We need the word boundary '\\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'.
.PP
We will implement some the examples above in the code examples section.
.SH "Characters and Abbreviations for Sets of Characters"
<center>.nf
.TS
l
-
l.
Element	Meaning
	Any character represents itself unless it has a special
regexp meaning. Thus
	A character that follows a backslash matches the character
itself except where mentioned below. For example if you
wished to match a literal caret at the beginning of a string
you would write
	This matches the ASCII bell character (BEL, 0x07).
	This matches the ASCII form feed character (FF, 0x0C).
	This matches the ASCII line feed character (LF, 0x0A, Unix newline).
	This matches the ASCII carriage return character (CR, 0x0D).
	This matches the ASCII horizontal tab character (HT, 0x09).
	This matches the ASCII vertical tab character (VT, 0x0B).
	This matches the Unicode character corresponding to the
hexadecimal number hhhh (between 0x0000 and 0xFFFF). &#92;0ooo
(i.e., \\zero ooo) matches the ASCII/Latin-1 character
corresponding to the octal number ooo (between 0 and 0377).
	This matches any character (including newline).
	This matches a digit (QChar::isDigit()).
	This matches a non-digit.
	This matches a whitespace (QChar::isSpace()).
	This matches a non-whitespace.
	This matches a word character (QChar::isLetterOrNumber() or '_').
	This matches a non-word character.

.TE
.fi
</center>
.PP
\fINote that the C++ compiler transforms backslashes in strings so to include a \fB&#92;\fR in a regexp you will need to enter it twice, i.e. \fB&#92;&#92;\fR.\fR
.SH "Sets of Characters"
Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets.
.PP
<center>.nf
.TS
l - l. The caret negates the character set if it occurs as the first character, i.e. immediately after the opening square bracket. For example, The dash is used to indicate a range of characters, for example
.TE
.fi
</center>
.PP
Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, \fB[0-9]\fR matches a digit in Western alphabets but \fB\\d\fR matches a digit in \fIany\fR alphabet.
.PP
Note that in most regexp literature sets of characters are called" character classes".
.SH "Quantifiers"
By default an expression is automatically quantified by \fB{1,1}\fR, i.e. it should occur exactly once. In the following list \fB\fIE\fR\fR stands for any expression. An expression is a character or an abbreviation for a set of characters or a set of characters in square brackets or any parenthesised expression.
.PP
<center>.nf
.TS
l
-
l.
	Matches zero or one occurrence of \fIE\fR. This quantifier
means "the previous expression is optional" since it will
match whether or not the expression occurs in the string. It
is the same as
	Matches one or more occurrences of \fIE\fR. This is the same
as
	Matches zero or more occurrences of \fIE\fR. This is the same
as
	Matches exactly \fIn\fR occurrences of the expression. This
is the same as repeating the expression \fIn\fR times. For
example,
	Matches at least \fIn\fR occurrences of the expression. This
is the same as
	Matches at most \fIm\fR occurrences of the expression. This
is the same as

.TE
.fi
</center>
.PP
(MAXINT is implementation dependent but will not be smaller than 1024.)
.PP
If we wish to apply a quantifier to more than just the preceding character we can use parentheses to group characters together in an expression. For example, \fBtag+\fR matches a 't' followed by an 'a' followed by at least one 'g', whereas \fB(tag)+\fR matches at least one occurrence of 'tag'.
.PP
Note that quantifiers are "greedy". They will match as much text as they can. For example, \fB0+\fR will match as many zeros as it can from the first zero it finds, e.g. '2.<u>000</u>5'. Quantifiers can be made non-greedy, see setMinimal().
.SH "Capturing Text"
Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expression \fBmail|letter|correspondence\fR that matches a string we know that \fIone\fR of the words matched but not which one. Using parentheses allows us to "capture" whatever is matched within their bounds, so if we used \fB(mail|letter|correspondence)\fR and matched this regexp against the string "I sent you some email" we can use the cap() or capturedTexts() functions to extract the matched characters, in this case 'mail'.
.PP
We can use captured text within the regexp itself. To refer to the captured text we use \fIbackreferences\fR which are indexed from 1, the same as for cap(). For example we could search for duplicate words in a string using \fB\\b(\\w+)\\W+&#92;1\\b\fR which means match a word boundary followed by one or more word characters followed by one or more non-word characters followed by the same text as the first parenthesised expression followed by a word boundary.
.PP
If we want to use parentheses purely for grouping and not for capturing we can use the non-capturing syntax, e.g. \fB(?:green|blue)\fR. Non-capturing parentheses begin '(?:' and end ')'. In this example we match either 'green' or 'blue' but we do not capture the match so we only know whether or not we matched but not which color we actually found. Using non-capturing parentheses is more efficient than using capturing parentheses since the regexp engine has to do less book-keeping.
.PP
Both capturing and non-capturing parentheses may be nested.
.SH "Assertions"
Assertions make some statement about the text at the point where they occur in the regexp but they do not match any characters. In the following list \fB\fIE\fR\fR stands for any expression.
.PP
<center>.nf
.TS
l - l. The caret signifies the beginning of the string. If you wish to match a literal The dollar signifies the end of the string. For example A word boundary. For example the regexp A non-word boundary. This assertion is true wherever Positive lookahead. This assertion is true if the expression matches at this point in the regexp. For example, Negative lookahead. This assertion is true if the expression does not match at this point in the regexp. For example,
.TE
.fi
</center>
.SH "Wildcard Matching (globbing)"
Most command shells such as \fIbash\fR or \fIcmd.exe\fR support "file globbing", the ability to identify a group of files by using wildcards. The setWildcard() function is used to switch between regexp and wildcard mode. Wildcard matching is much simpler than full regexps and has only four features:
.PP
<center>.nf
.TS
l
-
l.
	Any character represents itself apart from those mentioned
below. Thus
	This matches any single character. It is the same as
	This matches zero or more of any characters. It is the
same as

.TE
.fi
</center>
.PP
For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with \fB*.html\fR. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'.
.SH "Notes for Perl Users"
Most of the character class abbreviations supported by Perl are supported by QRegExp, see characters and abbreviations for sets of characters.
.PP
In QRegExp, apart from within character classes, \fC^\fR always signifies the start of the string, so carets must always be escaped unless used for that purpose. In Perl the meaning of caret varies automagically depending on where it occurs so escaping it is rarely necessary. The same applies to \fC$\fR which in QRegExp always signifies the end of the string.
.PP
QRegExp's quantifiers are the same as Perl's greedy quantifiers. Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regexp \fBro+?m\fR requires:
.PP
.nf
.br
    QRegExp rx( "ro+m" );
.br
    rx.setMinimal( TRUE );
.br
.fi
.PP
The equivalent of Perl's \fC/i\fR option is setCaseSensitive(FALSE).
.PP
Perl's \fC/g\fR option can be emulated using a loop.
.PP
In QRegExp \fB.\fR matches any character, therefore all QRegExp regexps have the equivalent of Perl's \fC/s\fR option. QRegExp does not have an equivalent to Perl's \fC/m\fR option, but this can be emulated in various ways for example by splitting the input into lines or by looping with a regexp that searches for newlines.
.PP
Because QRegExp is string oriented there are no \\A, \\Z or \\z assertions. The \\G assertion is not supported but can be emulated in a loop.
.PP
Perl's $& is cap(0) or capturedTexts()[0]. There are no QRegExp equivalents for $`, $' or $+. Perl's capturing variables, $1, $2,
... correspond to cap(1) or capturedTexts()[1], cap(2) or
capturedTexts()[2], etc.
.PP
To substitute a pattern use QString::replace().
.PP
Perl's extended \fC/x\fR syntax is not supported, nor are directives, e.g. (?i), or regexp comments, e.g. (?#comment). On the other hand, C++'s rules for literal strings can be used to achieve the same:
.PP
.nf
.br
    QRegExp mark( "\\\\b" // word boundary
.br
                  "[Mm]ark" // the word we want to match
.br
                );
.br
.fi
.PP
Both zero-width positive and zero-width negative lookahead assertions (?=pattern) and (?!pattern) are supported with the same syntax as Perl. Perl's lookbehind assertions, "independent" subexpressions and conditional expressions are not supported.
.PP
Non-capturing parentheses are also supported, with the same (?:pattern) syntax.
.PP
See QStringList::split() and QStringList::join() for equivalents to Perl's split and join functions.
.PP
Note: because C++ transforms &#92;'s they must be written \fItwice\fR in code, e.g. \fB&#92;b\fR must be written \fB&#92;&#92;b\fR.
.SH "Code Examples"
.nf
.br
    QRegExp rx( "^\\\\d\\\\d?$" );  // match integers 0 to 99
.br
    rx.search( "123" );         // returns -1 (no match)
.br
    rx.search( "-6" );          // returns -1 (no match)
.br
    rx.search( "6" );           // returns 0 (matched as position 0)
.br
.fi
.PP
The third string matches '<u>6</u>'. This is a simple validation regexp for integers in the range 0 to 99.
.PP
.nf
.br
    QRegExp rx( "^\\\\S+$" );     // match strings without whitespace
.br
    rx.search( "Hello world" ); // returns -1 (no match)
.br
    rx.search( "This_is-OK" );  // returns 0 (matched at position 0)
.br
.fi
.PP
The second string matches '<u>This_is-OK</u>'. We've used the character set abbreviation '\\S' (non-whitespace) and the anchors to match strings which contain no whitespace.
.PP
In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email'
.PP
.nf
.br
    QRegExp rx( "\\\\b(mail|letter|correspondence)\\\\b" );
.br
    rx.search( "I sent you an email" );     // returns -1 (no match)
.br
    rx.search( "Please write the letter" ); // returns 17
.br
.fi
.PP
The second string matches "Please write the <u>letter</u>". The word 'letter' is also captured (because of the parentheses). We can see what text we've captured like this:
.PP
.nf
.br
    QString captured = rx.cap( 1 ); // captured == "letter"
.br
.fi
.PP
This will capture the text from the first set of capturing parentheses (counting capturing left parentheses from left to right). The parentheses are counted from 1 since cap( 0 ) is the whole matched regexp (equivalent to '&' in most regexp engines).
.PP
.nf
.br
    QRegExp rx( "&(?!amp;)" );      // match ampersands but not &amp;
.br
    QString line1 = "This & that";
.br
    line1.replace( rx, "&amp;" );
.br
    // line1 == "This &amp; that"
.br
    QString line2 = "His &amp; hers & theirs";
.br
    line2.replace( rx, "&amp;" );
.br
    // line2 == "His &amp; hers &amp; theirs"
.br
.fi
.PP
Here we've passed the QRegExp to QString's replace() function to replace the matched text with new text.
.PP
.nf
.br
    QString str = "One Eric another Eirik, and an Ericsson."
.br
                    " How many Eiriks, Eric?";
.br
    QRegExp rx( "\\\\b(Eric|Eirik)\\\\b" ); // match Eric or Eirik
.br
    int pos = 0;    // where we are in the string
.br
    int count = 0;  // how many Eric and Eirik's we've counted
.br
    while ( pos >= 0 ) {
.br
        pos = rx.search( str, pos );
.br
        if ( pos >= 0 ) {
.br
            pos++;      // move along in str
.br
            count++;    // count our Eric or Eirik
.br
        }
.br
    }
.br
.fi
.PP
We've used the search() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time \fCpos++\fR we could have written \fCpos += rx.matchedLength()\fR to skip over the already matched string. The count will equal 3, matching 'One <u>Eric</u> another <u>Eirik</u>, and an Ericsson. How many Eiriks, <u>Eric</u>?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries.
.PP
One common use of regexps is to split lines of delimited data into their component fields.
.PP
.nf
.br
    str = "Trolltech AS\\twww.trolltech.com\\tNorway";
.br
    QString company, web, country;
.br
    rx.setPattern( "^([^\\t]+)\\t([^\\t]+)\\t([^\\t]+)$" );
.br
    if ( rx.search( str ) != -1 ) {
.br
        company = rx.cap( 1 );
.br
        web = rx.cap( 2 );
.br
        country = rx.cap( 3 );
.br
    }
.br
.fi
.PP
In this example our input lines have the format company name, web address and country. Unfortunately the regexp is rather long and not very versatile -- the code will break if we add any more fields. A simpler and better solution is to look for the separator, '\\t' in this case, and take the surrounding text. The QStringList split() function can take a separator string or regexp as an argument and split a string accordingly.
.PP
.nf
.br
    QStringList field = QStringList::split( "\\t", str );
.br
.fi
.PP
Here field[0] is the company, field[1] the web address and so on.
.PP
To imitate the matching of a shell we can use wildcard mode.
.PP
.nf
.br
    QRegExp rx( "*.html" );         // invalid regexp: * doesn't quantify anything
.br
    rx.setWildcard( TRUE );         // now it's a valid wildcard regexp
.br
    rx.exactMatch( "index.html" );  // returns TRUE
.br
    rx.exactMatch( "default.htm" ); // returns FALSE
.br
    rx.exactMatch( "readme.txt" );  // returns FALSE
.br
.fi
.PP
Wildcard matching can be convenient because of its simplicity, but any wildcard regexp can be defined using full regexps, e.g. \fB.*&#92;.html$\fR. Notice that we can't match both \fC.html\fR and \fC.htm\fR files with a wildcard unless we use \fB*.htm*\fR which will also match 'test.html.bak'. A full regexp gives us the precision we need, \fB.*&#92;.html?$\fR.
.PP
QRegExp can match case insensitively using setCaseSensitive(), and can use non-greedy matching, see setMinimal(). By default QRegExp uses full regexps but this can be changed with setWildcard(). Searching can be forward with search() or backward with searchRev(). Captured text can be accessed using capturedTexts() which returns a string list of all captured strings, or using cap() which returns the captured string for the given index. The pos() function takes a match index and returns the position in the string where the match was made (or -1 if there was no match).
.PP
See also QRegExpValidator, QString, QStringList, Miscellaneous Classes, Implicitly and Explicitly Shared Classes, and Non-GUI Classes.
.PP
.SS "Member Type Documentation"
.SH "QRegExp::CaretMode"
The CaretMode enum defines the different meanings of the caret (\fB^\fR) in a regular expression. The possible values are:
.TP
\fCQRegExp::CaretAtZero\fR - The caret corresponds to index 0 in the searched string.
.TP
\fCQRegExp::CaretAtOffset\fR - The caret corresponds to the start offset of the search.
.TP
\fCQRegExp::CaretWontMatch\fR - The caret never matches.
.SH MEMBER FUNCTION DOCUMENTATION
.SH "QRegExp::QRegExp ()"
Constructs an empty regexp.
.PP
See also isValid() and errorString().
.SH "QRegExp::QRegExp ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE )"
Constructs a regular expression object for the given \fIpattern\fR string. The pattern must be given using wildcard notation if \fIwildcard\fR is TRUE (default is FALSE). The pattern is case sensitive, unless \fIcaseSensitive\fR is FALSE. Matching is greedy (maximal), but can be changed by calling setMinimal().
.PP
See also setPattern(), setCaseSensitive(), setWildcard(), and setMinimal().
.SH "QRegExp::QRegExp ( const QRegExp & rx )"
Constructs a regular expression as a copy of \fIrx\fR.
.PP
See also operator=().
.SH "QRegExp::~QRegExp ()"
Destroys the regular expression and cleans up its internal data.
.SH "QString QRegExp::cap ( int nth = 0 )"
Returns the text captured by the \fInth\fR subexpression. The entire match has index 0 and the parenthesized subexpressions have indices starting from 1 (excluding non-capturing parentheses).
.PP
.nf
.br
    QRegExp rxlen( "(\\\\d+)(?:\\\\s*)(cm|inch)" );
.br
    int pos = rxlen.search( "Length: 189cm" );
.br
    if ( pos > -1 ) {
.br
        QString value = rxlen.cap( 1 ); // "189"
.br
        QString unit = rxlen.cap( 2 );  // "cm"
.br
        // ...
.br
    }
.br
.fi
.PP
The order of elements matched by cap() is as follows. The first element, cap(0), is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus cap(1) is the text of the first capturing parentheses, cap(2) is the text of the second, and so on.
.PP
Some patterns may lead to a number of matches which cannot be determined in advance, for example:
.PP
.nf
.br
    QRegExp rx( "(\\\\d+)" );
.br
    str = "Offsets: 12 14 99 231 7";
.br
    QStringList list;
.br
    pos = 0;
.br
    while ( pos >= 0 ) {
.br
        pos = rx.search( str, pos );
.br
        if ( pos > -1 ) {
.br
            list += rx.cap( 1 );
.br
            pos  += rx.matchedLength();
.br
        }
.br
    }
.br
    // list contains "12", "14", "99", "231", "7"
.br
.fi
.PP
See also capturedTexts(), pos(), exactMatch(), search(), and searchRev().
.PP
Examples:
.)l network/archivesearch/archivedialog.ui.h and regexptester/regexptester.cpp.
.SH "QStringList QRegExp::capturedTexts ()"
Returns a list of the captured text strings.
.PP
The first string in the list is the entire matched string. Each subsequent list element contains a string that matched a (capturing) subexpression of the regexp.
.PP
For example:
.PP
.nf
.br
        QRegExp rx( "(\\\\d+)(\\\\s*)(cm|inch(es)?)" );
.br
        int pos = rx.search( "Length: 36 inches" );
.br
        QStringList list = rx.capturedTexts();
.br
        // list is now ( "36 inches", "36", " ", "inches", "es" )
.br
.fi
.PP
The above example also captures elements that may be present but which we have no interest in. This problem can be solved by using non-capturing parentheses:
.PP
.nf
.br
        QRegExp rx( "(\\\\d+)(?:\\\\s*)(cm|inch(?:es)?)" );
.br
        int pos = rx.search( "Length: 36 inches" );
.br
        QStringList list = rx.capturedTexts();
.br
        // list is now ( "36 inches", "36", "inches" )
.br
.fi
.PP
Note that if you want to iterate over the list, you should iterate over a copy, e.g.
.PP
.nf
.br
        QStringList list = rx.capturedTexts();
.br
        QStringList::Iterator it = list.begin();
.br
        while( it != list.end() ) {
.br
            myProcessing( *it );
.br
            ++it;
.br
        }
.br
.fi
.PP
Some regexps can match an indeterminate number of times. For example if the input string is "Offsets: 12 14 99 231 7" and the regexp, \fCrx\fR, is \fB(&#92;d+)+\fR, we would hope to get a list of all the numbers matched. However, after calling \fCrx.search(str)\fR, capturedTexts() will return the list ( "12"," 12" ), i.e. the entire match was "12" and the first subexpression matched was "12". The correct approach is to use cap() in a loop.
.PP
The order of elements in the string list is as follows. The first element is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus capturedTexts()[1] is the text of the first capturing parentheses, capturedTexts()[2] is the text of the second and so on (corresponding to $1, $2, etc., in some other regexp languages).
.PP
See also cap(), pos(), exactMatch(), search(), and searchRev().
.SH "bool QRegExp::caseSensitive () const"
Returns TRUE if case sensitivity is enabled; otherwise returns FALSE. The default is TRUE.
.PP
See also setCaseSensitive().
.SH "QString QRegExp::errorString ()"
Returns a text string that explains why a regexp pattern is invalid the case being; otherwise returns "no error occurred".
.PP
See also isValid().
.PP
Example: regexptester/regexptester.cpp.
.SH "QString QRegExp::escape ( const QString & str )\fC [static]\fR"
Returns the string \fIstr\fR with every regexp special character escaped with a backslash. The special characters are $, (, ), *, +,
., ?, [, &#92;, ], ^, {, | and }.
.PP
Example:
.PP
.nf
.br
     s1 = QRegExp::escape( "bingo" );   // s1 == "bingo"
.br
     s2 = QRegExp::escape( "f(x)" );    // s2 == "f\\\\(x\\\\)"
.br
.fi
.PP
This function is useful to construct regexp patterns dynamically:
.PP
.nf
.br
    QRegExp rx( "(" + QRegExp::escape(name) +
.br
                "|" + QRegExp::escape(alias) + ")" );
.br
.fi
.SH "bool QRegExp::exactMatch ( const QString & str ) const"
Returns TRUE if \fIstr\fR is matched exactly by this regular expression; otherwise returns FALSE. You can determine how much of the string was matched by calling matchedLength().
.PP
For a given regexp string, R, exactMatch("R") is the equivalent of search("^R$") since exactMatch() effectively encloses the regexp in the start of string and end of string anchors, except that it sets matchedLength() differently.
.PP
For example, if the regular expression is \fBblue\fR, then exactMatch() returns TRUE only for input \fCblue\fR. For inputs \fCbluebell\fR, \fCblutak\fR and \fClightblue\fR, exactMatch() returns FALSE and matchedLength() will return 4, 3 and 0 respectively.
.PP
Although const, this function sets matchedLength(), capturedTexts() and pos().
.PP
See also search(), searchRev(), and QRegExpValidator.
.SH "bool QRegExp::isEmpty () const"
Returns TRUE if the pattern string is empty; otherwise returns FALSE.
.PP
If you call exactMatch() with an empty pattern on an empty string it will return TRUE; otherwise it returns FALSE since it operates over the whole string. If you call search() with an empty pattern on \fIany\fR string it will return the start offset (0 by default) because the empty pattern matches the 'emptiness' at the start of the string. In this case the length of the match returned by matchedLength() will be 0.
.PP
See QString::isEmpty().
.SH "bool QRegExp::isValid () const"
Returns TRUE if the regular expression is valid; otherwise returns FALSE. An invalid regular expression never matches.
.PP
The pattern \fB[a-z\fR is an example of an invalid pattern, since it lacks a closing square bracket.
.PP
Note that the validity of a regexp may also depend on the setting of the wildcard flag, for example \fB*.html\fR is a valid wildcard regexp but an invalid full regexp.
.PP
See also errorString().
.PP
Example: regexptester/regexptester.cpp.
.SH "int QRegExp::match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const"
\fBThis function is obsolete.\fR It is provided to keep old source working. We strongly advise against using it in new code.
.PP
Attempts to match in \fIstr\fR, starting from position \fIindex\fR. Returns the position of the match, or -1 if there was no match.
.PP
The length of the match is stored in \fI*len\fR, unless \fIlen\fR is a null pointer.
.PP
If \fIindexIsStart\fR is TRUE (the default), the position \fIindex\fR in the string will match the start of string anchor, \fB^\fR, in the regexp, if present. Otherwise, position 0 in \fIstr\fR will match.
.PP
Use search() and matchedLength() instead of this function.
.PP
See also QString::mid() and QConstString.
.PP
Example: qmag/qmag.cpp.
.SH "int QRegExp::matchedLength () const"
Returns the length of the last matched string, or -1 if there was no match.
.PP
See also exactMatch(), search(), and searchRev().
.PP
Examples:
.)l network/archivesearch/archivedialog.ui.h and regexptester/regexptester.cpp.
.SH "bool QRegExp::minimal () const"
Returns TRUE if minimal (non-greedy) matching is enabled; otherwise returns FALSE.
.PP
See also setMinimal().
.SH "int QRegExp::numCaptures () const"
Returns the number of captures contained in the regular expression.
.PP
Example: regexptester/regexptester.cpp.
.SH "bool QRegExp::operator!= ( const QRegExp & rx ) const"
Returns TRUE if this regular expression is not equal to \fIrx\fR; otherwise returns FALSE.
.PP
See also operator==().
.SH "QRegExp & QRegExp::operator= ( const QRegExp & rx )"
Copies the regular expression \fIrx\fR and returns a reference to the copy. The case sensitivity, wildcard and minimal matching options are also copied.
.SH "bool QRegExp::operator== ( const QRegExp & rx ) const"
Returns TRUE if this regular expression is equal to \fIrx\fR; otherwise returns FALSE.
.PP
Two QRegExp objects are equal if they have the same pattern strings and the same settings for case sensitivity, wildcard and minimal matching.
.SH "QString QRegExp::pattern () const"
Returns the pattern string of the regular expression. The pattern has either regular expression syntax or wildcard syntax, depending on wildcard().
.PP
See also setPattern().
.SH "int QRegExp::pos ( int nth = 0 )"
Returns the position of the \fInth\fR captured text in the searched string. If \fInth\fR is 0 (the default), pos() returns the position of the whole match.
.PP
Example:
.PP
.nf
.br
    QRegExp rx( "/([a-z]+)/([a-z]+)" );
.br
    rx.search( "Output /dev/null" );    // returns 7 (position of /dev/null)
.br
    rx.pos( 0 );                        // returns 7 (position of /dev/null)
.br
    rx.pos( 1 );                        // returns 8 (position of dev)
.br
    rx.pos( 2 );                        // returns 12 (position of null)
.br
.fi
.PP
For zero-length matches, pos() always returns -1. (For example, if cap(4) would return an empty string, pos(4) returns -1.) This is due to an implementation tradeoff.
.PP
See also capturedTexts(), exactMatch(), search(), and searchRev().
.SH "int QRegExp::search ( const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero ) const"
Attempts to find a match in \fIstr\fR from position \fIoffset\fR (0 by default). If \fIoffset\fR is -1, the search starts at the last character; if -2, at the next to last character; etc.
.PP
Returns the position of the first match, or -1 if there was no match.
.PP
The \fIcaretMode\fR parameter can be used to instruct whether \fB^\fR should match at index 0 or at \fIoffset\fR.
.PP
You might prefer to use QString::find(), QString::contains() or even QStringList::grep(). To replace matches use QString::replace().
.PP
Example:
.PP
.nf
.br
        QString str = "offsets: 1.23 .50 71.00 6.00";
.br
        QRegExp rx( "\\\\d*\\\\.\\\\d+" );    // primitive floating point matching
.br
        int count = 0;
.br
        int pos = 0;
.br
        while ( (pos = rx.search(str, pos)) != -1 ) {
.br
            count++;
.br
            pos += rx.matchedLength();
.br
        }
.br
        // pos will be 9, 14, 18 and finally 24; count will end up as 4
.br
.fi
.PP
Although const, this function sets matchedLength(), capturedTexts() and pos().
.PP
See also searchRev() and exactMatch().
.PP
Examples:
.)l network/archivesearch/archivedialog.ui.h and regexptester/regexptester.cpp.
.SH "int QRegExp::searchRev ( const QString & str, int offset = -1, CaretMode caretMode = CaretAtZero ) const"
Attempts to find a match backwards in \fIstr\fR from position \fIoffset\fR. If \fIoffset\fR is -1 (the default), the search starts at the last character; if -2, at the next to last character; etc.
.PP
Returns the position of the first match, or -1 if there was no match.
.PP
The \fIcaretMode\fR parameter can be used to instruct whether \fB^\fR should match at index 0 or at \fIoffset\fR.
.PP
Although const, this function sets matchedLength(), capturedTexts() and pos().
.PP
\fBWarning:\fR Searching backwards is much slower than searching forwards.
.PP
See also search() and exactMatch().
.SH "void QRegExp::setCaseSensitive ( bool sensitive )"
Sets case sensitive matching to \fIsensitive\fR.
.PP
If \fIsensitive\fR is TRUE, \fB&#92;.txt$\fR matches \fCreadme.txt\fR but not \fCREADME.TXT\fR.
.PP
See also caseSensitive().
.PP
Example: regexptester/regexptester.cpp.
.SH "void QRegExp::setMinimal ( bool minimal )"
Enables or disables minimal matching. If \fIminimal\fR is FALSE, matching is greedy (maximal) which is the default.
.PP
For example, suppose we have the input string "We must be <b>bold</b>, very <b>bold</b>!" and the pattern \fB<b>.*</b>\fR. With the default greedy (maximal) matching, the match is "We must be <u><b>bold</b>, very <b>bold</b></u>!". But with minimal (non-greedy) matching the first match is: "We must be <u><b>bold</b></u>, very <b>bold</b>!" and the second match is "We must be <b>bold</b>, very <u><b>bold</b></u>!". In practice we might use the pattern \fB<b>[^<]+</b>\fR instead, although this will still fail for nested tags.
.PP
See also minimal().
.PP
Examples:
.)l network/archivesearch/archivedialog.ui.h and regexptester/regexptester.cpp.
.SH "void QRegExp::setPattern ( const QString & pattern )"
Sets the pattern string to \fIpattern\fR. The case sensitivity, wildcard and minimal matching options are not changed.
.PP
See also pattern().
.SH "void QRegExp::setWildcard ( bool wildcard )"
Sets the wildcard mode for the regular expression. The default is FALSE.
.PP
Setting \fIwildcard\fR to TRUE enables simple shell-like wildcard matching. (See wildcard matching (globbing).)
.PP
For example, \fBr*.txt\fR matches the string \fCreadme.txt\fR in wildcard mode, but does not match \fCreadme\fR.
.PP
See also wildcard().
.PP
Example: regexptester/regexptester.cpp.
.SH "bool QRegExp::wildcard () const"
Returns TRUE if wildcard mode is enabled; otherwise returns FALSE. The default is FALSE.
.PP
See also setWildcard().

.SH "SEE ALSO"
.BR http://doc.trolltech.com/ntqregexp.html
.BR http://www.trolltech.com/faq/tech.html
.SH COPYRIGHT
Copyright 1992-2007 Trolltech ASA, http://www.trolltech.com.  See the
license file included in the distribution for a complete license
statement.
.SH AUTHOR
Generated automatically from the source code.
.SH BUGS
If you find a bug in Qt, please report it as described in
.BR http://doc.trolltech.com/bughowto.html .
Good bug reports help us to help you. Thank you.
.P
The definitive TQt documentation is provided in HTML format; it is
located at $TQTDIR/doc/html and can be read using TQt Assistant or with
a web browser. This man page is provided as a convenience for those
users who prefer man pages, although this format is not officially
supported by Trolltech. 
.P
If you find errors in this manual page, please report them to
.BR qt-bugs@trolltech.com .
Please include the name of the manual page (tqregexp.3qt) and the Qt
version (3.3.8).