File: qregexp.cpp

package info (click to toggle)
doxygen 1.4.2-4
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 14,816 kB
  • ctags: 22,819
  • sloc: cpp: 195,164; ansic: 30,489; lex: 19,840; sh: 1,661; python: 1,183; perl: 1,034; makefile: 451; yacc: 235
file content (1091 lines) | stat: -rw-r--r-- 26,285 bytes parent folder | download | duplicates (3)
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
/****************************************************************************
** 
**
** Implementation of QRegExp class
**
** Created : 950126
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include "qregexp.h"
#include <ctype.h>
#include <stdlib.h>

// NOT REVISED
/*!
  \class QRegExp qregexp.h
  \ingroup tools
  \ingroup misc
  \brief The QRegExp class provides pattern matching using regular
  expressions or wildcards.

  QRegExp knows these regexp primitives:
  <ul plain>
  <li><dfn>c</dfn> matches the character 'c'
  <li><dfn>.</dfn> matches any character
  <li><dfn>^</dfn> matches start of input
  <li><dfn>$</dfn>  matches end of input
  <li><dfn>[]</dfn> matches a defined set of characters - see below.
  <li><dfn>a*</dfn> matches a sequence of zero or more a's
  <li><dfn>a+</dfn> matches a sequence of one or more a's
  <li><dfn>a?</dfn> matches an optional a
  <li><dfn>\c</dfn> escape code for matching special characters such
  as \, [, *, +, . etc.
  <li><dfn>\t</dfn> matches the TAB character (9)
  <li><dfn>\n</dfn> matches newline (10)
  <li><dfn>\r</dfn> matches return (13)
  <li><dfn>\s</dfn> matches a white space (defined as any character
  for which QChar::isSpace() returns TRUE. This includes at least
  ASCII characters 9 (TAB), 10 (LF), 11 (VT), 12(FF), 13 (CR) and 32
  (Space)).
  <li><dfn>\d</dfn> matches a digit (defined as any character for
  which QChar::isDigit() returns TRUE. This includes at least ASCII
  characters '0'-'9').
  <li><dfn>\x1f6b</dfn> matches the character with unicode point U1f6b
  (hexadecimal 1f6b). \x0012 will match the ASCII/Latin1 character
  0x12 (18 decimal, 12 hexadecimal).
  <li><dfn>\022</dfn> matches the ASCII/Latin1 character 022 (18
  decimal, 22 octal).
  </ul>

  In wildcard mode, it only knows four primitives:
  <ul plain>
  <li><dfn>c</dfn> matches the character 'c'
  <li><dfn>?</dfn> matches any character
  <li><dfn>*</dfn> matches any sequence of characters
  <li><dfn>[]</dfn> matches a defined set of characters - see below.
  </ul>

  QRegExp supports Unicode both in the pattern strings and in the
  strings to be matched.

  When writing regular expressions in C++ code, remember that C++
  processes \ characters.  So in order to match e.g. a "." character,
  you must write "\\." in C++ source, not "\.".

  A character set matches a defined set of characters. For example,
  [BSD] matches any of 'B', 'D' and 'S'. Within a character set, the
  special characters '.', '*', '?', '^', '$', '+' and '[' lose their
  special meanings. The following special characters apply:
  <ul plain>
  <li><dfn>^</dfn> When placed first in the list, changes the
  character set to match any character \e not in the list. To include
  the character '^' itself in the set, escape it or place it anywhere
  but first.
  <li><dfn>-</dfn> Defines a range of characters. To include the
  character '-' itself in the set, escape it or place it last.
  <li><dfn>]</dfn> Ends the character set definition. To include the
  character ']' itself in the set, escape it or place it first (but
  after the negation operator '^', if present)
  </ul>
  Thus, [a-zA-Z0-9.] matches upper and lower case ASCII letters,
  digits and dot; and [^\s] matches everything except white space.

  \bug Case insensitive matching is not supported for non-ASCII/Latin1
  (non-8bit) characters. Any character with a non-zero QChar.row() is
  matched case sensitively even if the QRegExp is in case insensitive
  mode.

  \note In Qt 3.0, the language of regular expressions will contain
  five more special characters, namely '(', ')', '{', '|' and '}'. To
  ease porting, it's a good idea to escape these characters with a
  backslash in all the regular expressions you'll write from now on.
*/


//
// The regexp pattern is internally represented as an array of uints,
// each element containing an 16-bit character or a 32-bit code
// (listed below).  User-defined character classes (e.g. [a-zA-Z])
// are encoded as this:
// uint no:	1		2		3		...
// value:	CCL | n		from | to	from | to
//
// where n is the (16-bit) number of following range definitions and
// from and to define the ranges inclusive. from <= to is always true,
// otherwise it is a built-in charclass (Pxx, eg \s - PWS). Single
// characters in the class are coded as from==to.  Negated classes
// (e.g. [^a-z]) use CCN instead of CCL.

const uint END	= 0x00000000;
const uint PWS	= 0x10010000;		// predef charclass: whitespace (\s)
const uint PDG	= 0x10020000;		// predef charclass: digit (\d)
const uint CCL	= 0x20010000;		// character class	[]
const uint CCN	= 0x20020000;		// neg character class	[^]
const uint CHR	= 0x40000000;		// character
const uint BOL	= 0x80010000;		// beginning of line	^
const uint EOL	= 0x80020000;		// end of line		$
const uint BOW	= 0x80030000;		// beginning of word	\<
const uint EOW	= 0x80040000;		// end of word		\>
const uint ANY	= 0x80050000;		// any character	.
const uint CLO	= 0x80070000;		// Kleene closure	*
const uint OPT	= 0x80080000;		// Optional closure	?

const uint MCC  = 0x20000000;		// character class bitmask
const uint MCD  = 0xffff0000;		// code mask
const uint MVL  = 0x0000ffff;		// value mask

//
// QRegExp::error codes (internal)
//

const int PatOk		= 0;			// pattern ok
const int PatNull	= 1;			// no pattern defined
const int PatSyntax	= 2;			// pattern syntax error
const int PatOverflow	= 4;			// pattern too long


/*****************************************************************************
  QRegExp member functions
 *****************************************************************************/

/*!
  Constructs an empty regular expression.
*/

QRegExp::QRegExp()
{
    rxdata = 0;
    cs = TRUE;
    wc = FALSE;
    error = PatOk;
}

/*!
  Constructs a regular expression.

  \arg \e pattern is the regular expression pattern string.
  \arg \e caseSensitive specifies whether or not to use case sensitive
  matching.
  \arg \e wildcard specifies whether the pattern string should be used for
  wildcard matching (also called globbing expression), normally used for
  matching file names.

  \sa setWildcard()
*/

QRegExp::QRegExp( const QString &pattern, bool caseSensitive, bool wildcard )
{
    rxstring = pattern;
    rxdata = 0;
    cs = caseSensitive;
    wc = wildcard;
    compile();
}

/*!
  Constructs a regular expression which is a copy of \e r.
  \sa operator=(const QRegExp&)
*/

QRegExp::QRegExp( const QRegExp &r )
{
    rxstring = r.pattern();
    rxdata = 0;
    cs = r.caseSensitive();
    wc = r.wildcard();
    compile();
}

/*!
  Destructs the regular expression and cleans up its internal data.
*/

QRegExp::~QRegExp()
{
    if ( rxdata )                      // Avoid purify complaints
	delete [] rxdata;
}

/*!
  Copies the regexp \e r and returns a reference to this regexp.
  The case sensitivity and wildcard options are copied, as well.
*/

QRegExp &QRegExp::operator=( const QRegExp &r )
{
    rxstring = r.rxstring;
    cs = r.cs;
    wc = r.wc;
    compile();
    return *this;
}

/*!
  \obsolete
  Consider using setPattern() instead of this method.

  Sets the pattern string to \e pattern and returns a reference to this regexp.
  The case sensitivity or wildcard options do not change.
*/

QRegExp &QRegExp::operator=( const QString &pattern )
{
    rxstring = pattern;
    compile();
    return *this;
}


/*!
  Returns TRUE if this regexp is equal to \e r.

  Two regexp objects are equal if they have equal pattern strings,
  case sensitivity options and wildcard options.
*/

bool QRegExp::operator==( const QRegExp &r ) const
{
    return rxstring == r.rxstring && cs == r.cs && wc == r.wc;
}

/*!
  \fn bool QRegExp::operator!=( const QRegExp &r ) const

  Returns TRUE if this regexp is \e not equal to \e r.

  \sa operator==()
*/

/*!
  \fn bool QRegExp::isEmpty() const
  Returns TRUE if the regexp is empty.
*/

/*!
  \fn bool QRegExp::isValid() const
  Returns TRUE if the regexp is valid, or FALSE if it is invalid.

  The pattern "[a-z" is an example of an invalid pattern, since it lacks a
  closing bracket.
*/


/*!
  \fn bool QRegExp::wildcard() const
  Returns TRUE if wildcard mode is on, otherwise FALSE. \sa setWildcard().
*/

/*!
  Sets the wildcard option for the regular expression.	The default
  is FALSE.

  Setting \e wildcard to TRUE makes it convenient to match filenames
  instead of plain text.

  For example, "qr*.cpp" matches the string "qregexp.cpp" in wildcard mode,
  but not "qicpp" (which would be matched in normal mode).

  \sa wildcard()
*/

void QRegExp::setWildcard( bool wildcard )
{
    if ( wildcard != wc ) {
	wc = wildcard;
	compile();
    }
}

/*!
  \fn bool QRegExp::caseSensitive() const

  Returns TRUE if case sensitivity is enabled, otherwise FALSE.	 The
  default is TRUE.

  \sa setCaseSensitive()
*/

/*!
  Enables or disables case sensitive matching.

  In case sensitive mode, "a.e" matches "axe" but not "Axe".

  See also: caseSensitive()
*/

void QRegExp::setCaseSensitive( bool enable )
{
    if ( cs != enable ) {
	cs = enable;
	compile();
    }
}


/*!
  \fn QString QRegExp::pattern() const
  Returns the pattern string of the regexp.
*/


/*!
  \fn void QRegExp::setPattern(const QString & pattern)
  Sets the pattern string to \a pattern and returns a reference to this regexp.
  The case sensitivity or wildcard options do not change.
*/

static inline bool iswordchar( int x )
{
    return isalnum(x) || x == '_';	//# Only 8-bit support
}


/*!
  \internal
  Match character class
*/

static bool matchcharclass( uint *rxd, QChar c )
{
    uint *d = rxd;
    uint clcode = *d & MCD;
    bool neg = clcode == CCN;
    if ( clcode != CCL && clcode != CCN)
	qWarning("QRegExp: Internal error, please report to qt-bugs@trolltech.com");
    uint numFields = *d & MVL;
    uint cval = (((uint)(c.row())) << 8) | ((uint)c.cell());
    bool found = FALSE;
    for ( int i = 0; i < (int)numFields; i++ ) {
	d++;
	if ( *d == PWS && c.isSpace() ) {
	    found = TRUE;
	    break;
	}
	if ( *d == PDG && c.isDigit() ) {
	    found = TRUE;
	    break;
	}
	else {
	    uint from = ( *d & MCD ) >> 16;
	    uint to = *d & MVL;
	    if ( (cval >= from) && (cval <= to) ) {
		found = TRUE;
		break;
	    }
	}
    }
    return neg ? !found : found;
}



/*
  Internal: Recursively match string.
*/

static int matchstring( uint *rxd, const QChar *str, uint strlength,
			const QChar *bol, bool cs )
{
    const QChar *p = str;
    const QChar *start = p;
    uint pl = strlength;
    uint *d = rxd;

    //### in all cases here: handle pl == 0! (don't read past strlen)
    while ( *d ) {
	if ( *d & CHR ) {			// match char
	    if ( !pl )
		return -1;
	    QChar c( *d );
	    if ( !cs && !c.row() ) {		// case insensitive, #Only 8bit
		if ( p->row() || tolower(p->cell()) != c.cell() )
		    return -1;
		p++;
		pl--;
	    } else {				// case insensitive
		if ( *p != c )
		    return -1;
		p++;
		pl--;
	    }
	    d++;
	}
	else if ( *d & MCC ) {			// match char class
	    if ( !pl )
		return -1;
	    if ( !matchcharclass( d, *p ) )
		return -1;
	    p++;
	    pl--;
	    d += (*d & MVL) + 1;
	}
	else switch ( *d++ ) {
	    case PWS:				// match whitespace
		if ( !pl || !p->isSpace() )
		    return -1;
		p++;
		pl--;
		break;
	    case PDG:				// match digits
		if ( !pl || !p->isDigit() )
		    return -1;
		p++;
		pl--;
		break;
	    case ANY:				// match anything
		if ( !pl )
		    return -1;
		p++;
		pl--;
		break;
	    case BOL:				// match beginning of line
		if ( p != bol )
		    return -1;
		break;
	    case EOL:				// match end of line
		if ( pl )
		    return -1;
		break;
	    case BOW:				// match beginning of word
		if ( !iswordchar(*p) || (p > bol && iswordchar(*(p-1)) ) )
		    return -1;
		break;
	    case EOW:				// match end of word
		if ( iswordchar(*p) || p == bol || !iswordchar(*(p-1)) )
		    return -1;
		break;
	    case CLO:				// Kleene closure
		{
		const QChar *first_p = p;
		if ( *d & CHR ) {		// match char
		    QChar c( *d );
		    if ( !cs && !c.row() ) {	// case insensitive, #only 8bit
			while ( pl && !p->row() && tolower(p->cell())==c.cell() ) {
			    p++;
			    pl--;
			}
		    }
		    else {			// case sensitive
			while ( pl && *p == c ) {
			    p++;
			    pl--;
			}
		    }
		    d++;
		}
		else if ( *d & MCC ) {			// match char class
		    while( pl && matchcharclass( d, *p ) ) {
			p++;
			pl--;
		    }
		    d += (*d & MVL) + 1;
		}
		else if ( *d == PWS ) {
		    while ( pl && p->isSpace() ) {
			p++;
			pl--;
		    }
		    d++;
		}
		else if ( *d == PDG ) {
		    while ( pl && p->isDigit() ) {
			p++;
			pl--;
		    }
		    d++;
		}
		else if ( *d == ANY ) {
		    p += pl;
		    pl = 0;
		    d++;
		}
		else {
		    return -1;			// error
		}
		d++;				// skip CLO's END
		while ( p >= first_p ) {	// go backwards
		    int end = matchstring( d, p, pl, bol, cs );
		    if ( end >= 0 )
			return ( p - start ) + end;
		    if ( !p )
			return -1;
		    --p;
		    ++pl;
		}
		}
		return -1;
	    case OPT:				// optional closure
		{
		const QChar *first_p = p;
		if ( *d & CHR ) {		// match char
		    QChar c( *d );
		    if ( !cs && !c.row() ) {	// case insensitive, #only 8bit
			if ( pl && !p->row() && tolower(p->cell()) == c.cell() ) {
			    p++;
			    pl--;
			}
		    }
		    else {			// case sensitive
			if ( pl && *p == c ) {
			    p++;
			    pl--;
			}
		    }
		    d++;
		}
		else if ( *d & MCC ) {			// match char class
		    if ( pl && matchcharclass( d, *p ) ) {
			p++;
			pl--;
		    }
		    d += (*d & MVL) + 1;
		}
		else if ( *d == PWS ) {
		    if ( pl && p->isSpace() ) {
			p++;
			pl--;
		    }
		    d++;
		}
		else if ( *d == PDG ) {
		    if ( pl && p->isDigit() ) {
			p++;
			pl--;
		    }
		    d++;
		}
		else if ( *d == ANY ) {
		    if ( pl ) {
			p++;
			pl--;
		    }
		    d++;
		}
		else {
		    return -1;			// error
		}
		d++;				// skip OPT's END
		while ( p >= first_p ) {	// go backwards
		    int end = matchstring( d, p, pl, bol, cs );
		    if ( end >= 0 )
			return ( p - start ) + end;
		    if ( !p )
			return -1;
		    --p;
		    ++pl;
		}
		}
		return -1;

	    default:				// error
		return -1;
	}
    }
    return p - start;
}


/*!
  \internal
  Recursively match string.
*/

// This is obsolete now, but since it is protected (not private), it
// is still implemented on the off-chance that somebody has made a
// class derived from QRegExp and calls this directly.
// Qt 3.0: Remove this?


const QChar *QRegExp::matchstr( uint *rxd, const QChar *str, uint strlength,
				const QChar *bol ) const
{
    int len = matchstring( rxd, str, strlength, bol, cs );
    if ( len < 0 )
	return 0;
    return str + len;
}

/*!
  Attempts to match in \e str, starting from position \e index.
  Returns the position of the match, or -1 if there was no match.

  If \e len is not a null pointer, the length of the match is stored in
  \e *len.

  If \e indexIsStart is TRUE (the default), the position \e index in
  the string will match the start-of-input primitive (^) in the
  regexp, if present. Otherwise, position 0 in \e str will match.

  Example:
  \code
    QRegExp r("[0-9]*\\.[0-9]+");		// matches floating point
    int len;
    r.match("pi = 3.1416", 0, &len);		// returns 5, len == 6
  \endcode

  \note In Qt 3.0, this function will be replaced by find().
*/

int QRegExp::match( const QString &str, int index, int *len,
		    bool indexIsStart ) const
{
    if ( !isValid() || isEmpty() )
	return -1;
    if ( str.length() < (uint)index )
	return -1;
    const QChar *start = str.unicode();
    const QChar *p = start + index;
    uint pl = str.length() - index;
    uint *d  = rxdata;
    int ep = -1;

    if ( *d == BOL ) {				// match from beginning of line
	ep = matchstring( d, p, pl, indexIsStart ? p : start, cs );
    } else {
	if ( *d & CHR ) {
	    QChar c( *d );
	    if ( !cs && !c.row() ) {		// case sensitive, # only 8bit
		while ( pl && ( p->row() || tolower(p->cell()) != c.cell() ) ) {
		    p++;
		    pl--;
		}
	    } else {				// case insensitive
		while ( pl && *p != c ) {
		    p++;
		    pl--;
		}
	    }
	}
	while( 1 ) {				// regular match
	    ep = matchstring( d, p, pl, indexIsStart ? start+index : start, cs );
	    if ( ep >= 0 )
		break;
	    if ( !pl )
		break;
	    p++;
	    pl--;
	}
    }
    if ( len )
	*len = ep >= 0 ? ep : 0;      // No match -> 0, for historical reasons
    return ep >= 0 ? (int)(p - start) : -1;		// return index;
}

/*! \fn int QRegExp::find( const QString& str, int index )

  Attempts to match in \e str, starting from position \e index.
  Returns the position of the match, or -1 if there was no match.

  \sa match()
*/

//
// Translate wildcard pattern to standard regexp pattern.
// Ex:	 *.cpp	==> ^.*\.cpp$
//

static QString wc2rx( const QString &pattern )
{
    int patlen = (int)pattern.length();
    QString wcpattern = QString::fromLatin1("^");

    QChar c;
    for( int i = 0; i < patlen; i++ ) {
	c = pattern[i];
	switch ( (char)c ) {
	case '*':				// '*' ==> '.*'
	    wcpattern += '.';
	    break;
	case '?':				// '?' ==> '.'
	    c = '.';
	    break;
	case '.':				// quote special regexp chars
	case '+':
	case '\\':
	case '$':
	case '^':
	    wcpattern += '\\';
	    break;
	case '[':
	    if ( (char)pattern[i+1] == '^' ) { // don't quote '^' after '['
		wcpattern += '[';
		c = pattern[i+1];
		i++;
	    }
	    break;
	}
	wcpattern += c;

    }
    wcpattern += '$';
    return wcpattern;				// return new regexp pattern
}


//
// Internal: Get char value and increment pointer.
//

static uint char_val( const QChar **str, uint *strlength )   // get char value
{
    const QChar *p = *str;
    uint pl = *strlength;
    uint len = 1;
    uint v = 0;
    if ( (char)*p == '\\' ) {			// escaped code
	p++;
	pl--;
	if ( !pl ) {				// it is just a '\'
	    (*str)++;
	    (*strlength)--;
	    return '\\';
	}
	len++;					// length at least 2
	int i;
	char c;
	char ch = tolower((char)*p);
	switch ( ch ) {
	    case 'b':  v = '\b';  break;	// bell
	    case 'f':  v = '\f';  break;	// form feed
	    case 'n':  v = '\n';  break;	// newline
	    case 'r':  v = '\r';  break;	// return
	    case 't':  v = '\t';  break;	// tab
	    case 's':  v = PWS; break;		// whitespace charclass
	    case 'd':  v = PDG; break;		// digit charclass
	    case '<':  v = BOW; break;		// word beginning matcher
	    case '>':  v = EOW; break;		// word ending matcher

	    case 'x': {				// hex code
		p++;
		pl--;
		for ( i = 0; (i < 4) && pl; i++ ) {	//up to 4 hex digits
		    c = tolower((char)*p);
		    bool a = ( c >= 'a' && c <= 'f' );
		    if ( (c >= '0' && c <= '9') || a ) {
			v <<= 4;
			v += a ? 10 + c - 'a' : c - '0';
			len++;
		    }
		    else {
			break;
		    }
		    p++;
		    pl--;
		}
	    }
	    break;

	    default: {
		if ( ch >= '0' && ch <= '7' ) {	//octal code
		    len--;
		    for ( i = 0; (i < 3) && pl; i++ ) {	// up to 3 oct digits
			c = (char)*p;
			if ( c >= '0' && c <= '7' ) {
			    v <<= 3;
			    v += c - '0';
			    len++;
			}
			else {
			    break;
			}
			p++;
			pl--;
		    }
		}
		else {				// not an octal number
		    v = (((uint)(p->row())) << 8) | ((uint)p->cell());
		}
	    }
	}
    } else {
	v = (((uint)(p->row())) << 8) | ((uint)p->cell());
    }
    *str += len;
    *strlength -= len;
    return v;
}


#if defined(DEBUG)
static uint *dump( uint *p )
{
    while ( *p != END ) {
	if ( *p & CHR ) {
	    QChar uc = (QChar)*p;
	    char c = (char)uc;
	    uint u = (((uint)(uc.row())) << 8) | ((uint)uc.cell());
	    qDebug( "\tCHR\tU%04x (%c)", u, (c ? c : ' '));
	    p++;
	}
	else if ( *p & MCC ) {
	    uint clcode = *p & MCD;
	    uint numFields = *p & MVL;
	    if ( clcode == CCL )
		qDebug( "\tCCL\t%i", numFields );
	    else if ( clcode == CCN )
		qDebug( "\tCCN\t%i", numFields );
	    else
		qDebug("coding error!");
	    for ( int i = 0; i < (int)numFields; i++ ) {
		p++;
		if ( *p == PWS )
		    qDebug( "\t\tPWS" );
		else if ( *p == PDG )
		    qDebug( "\t\tPDG" );
		else {
		    uint from = ( *p & MCD ) >> 16;
		    uint to = *p & MVL;
		    char fc = (char)QChar(from);
		    char tc = (char)QChar(to);
		    qDebug( "\t\tU%04x (%c) - U%04x (%c)", from,
			   (fc ? fc : ' '), to, (tc ? tc : ' ') );
		}
	    }
	    p++;
	}
	else switch ( *p++ ) {
	    case PWS:
		qDebug( "\tPWS" );
		break;
	    case PDG:
		qDebug( "\tPDG" );
		break;
	    case BOL:
		qDebug( "\tBOL" );
		break;
	    case EOL:
		qDebug( "\tEOL" );
		break;
	    case BOW:
		qDebug( "\tBOW" );
		break;
	    case EOW:
		qDebug( "\tEOW" );
		break;
	    case ANY:
		qDebug( "\tANY" );
		break;
	    case CLO:
		qDebug( "\tCLO" );
		p = dump( p );
		break;
	    case OPT:
		qDebug( "\tOPT" );
		p = dump( p );
		break;
	}
    }
    qDebug( "\tEND" );
    return p+1;
}
#endif // DEBUG


static const int maxlen = 1024;			// max length of regexp array
static uint rxarray[ maxlen ];			// tmp regexp array

/*!
  \internal
  Compiles the regular expression and stores the result in rxdata.
  The 'error' flag is set to non-zero if an error is detected.
  NOTE! This function is not reentrant!
*/

void QRegExp::compile()
{
    if ( rxdata ) {				// delete old data
	delete [] rxdata;
	rxdata = 0;
    }
    if ( rxstring.isEmpty() ) {			// no regexp pattern set
	error = PatNull;
	return;
    }

    error = PatOk;				// assume pattern is ok

    QString pattern;
    if ( wc )
	pattern = wc2rx(rxstring);
    else
	pattern = rxstring;
    const QChar *start = pattern.unicode();	// pattern pointer
    const QChar *p = start;			// pattern pointer
    uint pl = pattern.length();
    uint *d = rxarray;				// data pointer
    uint *prev_d = 0;

#define GEN(x)	*d++ = (x)

    while ( pl ) {
	char ch = (char)*p;
	switch ( ch ) {

	    case '^':				// beginning of line
		prev_d = d;
		GEN( p == start ? BOL : (CHR | ch) );
		p++;
		pl--;
		break;

	    case '$':				// end of line
		prev_d = d;
		GEN( pl == 1 ? EOL : (CHR | ch) );
		p++;
		pl--;
		break;

	    case '.':				// any char
		prev_d = d;
		GEN( ANY );
		p++;
		pl--;
		break;

	    case '[':				// character class
		{
		prev_d = d;
		p++;
		pl--;
		if ( !pl ) {
		    error = PatSyntax;
		    return;
		}
		bool firstIsEscaped = ( (char)*p == '\\' );
		uint cch = char_val( &p, &pl );
		if ( cch == '^' && !firstIsEscaped ) {	// negate!
		    GEN( CCN );
		    if ( !pl ) {
			error = PatSyntax;
			return;
		    }
		    cch = char_val( &p, &pl );
		} else {
		    GEN( CCL );
		}
		uint numFields = 0;
		while ( pl ) {
		    if ((pl>2) && ((char)*p == '-') && ((char)*(p+1) != ']')) {
			// Found a range
		       	char_val( &p, &pl ); // Read the '-'
			uint cch2 = char_val( &p, &pl ); // Read the range end
			if ( cch > cch2 ) { 		// swap start and stop
			    int tmp = cch;
			    cch = cch2;
			    cch2 = tmp;
			}
			GEN( (cch << 16) | cch2 );	// from < to
			numFields++;
		    }
		    else {
			// Found a single character
			if ( cch & MCD ) // It's a code; will not be mistaken
			    GEN( cch );	 // for a range, since from > to
			else
			    GEN( (cch << 16) | cch ); // from == to range
			numFields++;
		    }
		    if ( d >= rxarray + maxlen ) {	// pattern too long
			error = PatOverflow;		
			return;
		    }
		    if ( !pl ) {		// At least ']' should be left
			error = PatSyntax;
			return;
		    }
		    bool nextIsEscaped = ( (char)*p == '\\' );
		    cch = char_val( &p, &pl );
		    if ( cch == (uint)']' && !nextIsEscaped )
			break;
		    if ( !pl ) {		// End, should have seen ']'
			error = PatSyntax;
			return;
		    }
		}
		*prev_d |= numFields;		// Store number of fields
		}
		break;

	    case '*':				// Kleene closure, or
	    case '+':				// positive closure, or
	    case '?':				// optional closure
		{
		if ( prev_d == 0 ) {		// no previous expression
		    error = PatSyntax;		// empty closure
		    return;
		}
		switch ( *prev_d ) {		// test if invalid closure
		    case BOL:
		    case BOW:
		    case EOW:
		    case CLO:
		    case OPT:
			error = PatSyntax;
			return;
		}
		int ddiff = d - prev_d;
		if ( *p == '+' ) {		// convert to Kleene closure
		    if ( d + ddiff >= rxarray + maxlen ) {
			error = PatOverflow;	// pattern too long
			return;
		    }
		    memcpy( d, prev_d, ddiff*sizeof(uint) );
		    d += ddiff;
		    prev_d += ddiff;
		}
		memmove( prev_d+1, prev_d, ddiff*sizeof(uint) );
		*prev_d = ch == '?' ? OPT : CLO;
		d++;
		GEN( END );
		p++;
		pl--;
		}
		break;

	    default:
		{
		prev_d = d;
		uint cv = char_val( &p, &pl );
		if ( cv & MCD ) {			// It's a code
		    GEN( cv );
		}
		else {
		    if ( !cs && cv <= 0xff )		// #only 8bit support
			cv = tolower( cv );
		    GEN( CHR | cv );
		}
		}
	}
	if ( d >= rxarray + maxlen ) {		// oops!
	    error = PatOverflow;		// pattern too long
	    return;
	}
    }
    GEN( END );
    int len = d - rxarray;
    rxdata = new uint[ len ];			// copy from rxarray to rxdata
    CHECK_PTR( rxdata );
    memcpy( rxdata, rxarray, len*sizeof(uint) );
#if defined(DEBUG)
    //dump( rxdata );	// uncomment this line for debugging
#endif
}