forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Matcher.java
1959 lines (1804 loc) · 81.5 KB
/
Matcher.java
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
/*
* Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.regex;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* An engine that performs match operations on a {@linkplain
* java.lang.CharSequence character sequence} by interpreting a {@link Pattern}.
*
* <p> A matcher is created from a pattern by invoking the pattern's {@link
* Pattern#matcher matcher} method. Once created, a matcher can be used to
* perform three different kinds of match operations:
*
* <ul>
*
* <li><p> The {@link #matches matches} method attempts to match the entire
* input sequence against the pattern. </p></li>
*
* <li><p> The {@link #lookingAt lookingAt} method attempts to match the
* input sequence, starting at the beginning, against the pattern. </p></li>
*
* <li><p> The {@link #find find} method scans the input sequence looking
* for the next subsequence that matches the pattern. </p></li>
*
* </ul>
*
* <p> Each of these methods returns a boolean indicating success or failure.
* More information about a successful match can be obtained by querying the
* state of the matcher.
*
* <p> A matcher finds matches in a subset of its input called the
* <i>region</i>. By default, the region contains all of the matcher's input.
* The region can be modified via the {@link #region(int, int) region} method
* and queried via the {@link #regionStart() regionStart} and {@link
* #regionEnd() regionEnd} methods. The way that the region boundaries interact
* with some pattern constructs can be changed. See {@link
* #useAnchoringBounds(boolean) useAnchoringBounds} and {@link
* #useTransparentBounds(boolean) useTransparentBounds} for more details.
*
* <p> This class also defines methods for replacing matched subsequences with
* new strings whose contents can, if desired, be computed from the match
* result. The {@link #appendReplacement appendReplacement} and {@link
* #appendTail appendTail} methods can be used in tandem in order to collect
* the result into an existing string buffer or string builder. Alternatively,
* the more convenient {@link #replaceAll replaceAll} method can be used to
* create a string in which every matching subsequence in the input sequence
* is replaced.
*
* <p> The explicit state of a matcher includes the start and end indices of
* the most recent successful match. It also includes the start and end
* indices of the input subsequence captured by each <a
* href="Pattern.html#cg">capturing group</a> in the pattern as well as a total
* count of such subsequences. As a convenience, methods are also provided for
* returning these captured subsequences in string form.
*
* <p> The explicit state of a matcher is initially undefined; attempting to
* query any part of it before a successful match will cause an {@link
* IllegalStateException} to be thrown. The explicit state of a matcher is
* recomputed by every match operation.
*
* <p> The implicit state of a matcher includes the input character sequence as
* well as the <i>append position</i>, which is initially zero and is updated
* by the {@link #appendReplacement appendReplacement} method.
*
* <p> A matcher may be reset explicitly by invoking its {@link #reset()}
* method or, if a new input sequence is desired, its {@link
* #reset(java.lang.CharSequence) reset(CharSequence)} method. Resetting a
* matcher discards its explicit state information and sets the append position
* to zero.
*
* <p> Instances of this class are not safe for use by multiple concurrent
* threads. </p>
*
* @author Mike McCloskey
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @spec JSR-51
* @since 1.4
*/
// 对接正则表达式与待检索字符串,以完成匹配任务
public final class Matcher implements MatchResult {
/**
* Matcher state used by the last node.
* NOANCHOR is used when a match does not have to consume all of the input.
* ENDANCHOR is the mode used for matching all the input.
*/
static final int ENDANCHOR = 1;
static final int NOANCHOR = 0;
int acceptMode = NOANCHOR;
/**
* The Pattern object that created this Matcher.
*/
Pattern parentPattern;
/**
* The storage used by groups. They may contain invalid values if
* a group was skipped during the matching.
*/
int[] groups;
/**
* The range within the sequence that is to be matched. Anchors
* will match at these "hard" boundaries. Changing the region
* changes these values.
*/
int from, to;
/**
* Lookbehind uses this value to ensure that the subexpression
* match ends at the point where the lookbehind was encountered.
*/
int lookbehindTo;
/**
* The original string being matched.
*/
CharSequence text;
/**
* The range of string that last matched the pattern. If the last
* match failed then first is -1; last initially holds 0 then it
* holds the index of the end of the last match (which is where the
* next search starts).
*/
int first = -1, last = 0;
/**
* The end index of what matched in the last match operation.
*/
int oldLast = -1;
/**
* The index of the last position appended in a substitution.
*/
int lastAppendPosition = 0;
/**
* Storage used by nodes to tell what repetition they are on in
* a pattern, and where groups begin. The nodes themselves are stateless,
* so they rely on this field to hold state during a match.
*/
int[] locals;
/**
* Storage used by top greedy Loop node to store a specific hash set to
* keep the beginning index of the failed repetition match. The nodes
* themselves are stateless, so they rely on this field to hold state
* during a match.
*/
IntHashSet[] localsPos;
/**
* Boolean indicating whether or not more input could change
* the results of the last match.
*
* If hitEnd is true, and a match was found, then more input
* might cause a different match to be found.
* If hitEnd is true and a match was not found, then more
* input could cause a match to be found.
* If hitEnd is false and a match was found, then more input
* will not change the match.
* If hitEnd is false and a match was not found, then more
* input will not cause a match to be found.
*/
boolean hitEnd;
/**
* Boolean indicating whether or not more input could change
* a positive match into a negative one.
*
* If requireEnd is true, and a match was found, then more
* input could cause the match to be lost.
* If requireEnd is false and a match was found, then more
* input might change the match but the match won't be lost.
* If a match was not found, then requireEnd has no meaning.
*/
boolean requireEnd;
/**
* If transparentBounds is true then the boundaries of this
* matcher's region are transparent to lookahead, lookbehind,
* and boundary matching constructs that try to see beyond them.
*/
boolean transparentBounds = false;
/**
* If anchoringBounds is true then the boundaries of this
* matcher's region match anchors such as ^ and $.
*/
boolean anchoringBounds = true;
/**
* Number of times this matcher's state has been modified
*/
int modCount;
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* No default constructor.
*/
Matcher() {
}
/**
* All matchers have the state used by Pattern during a match.
*/
Matcher(Pattern parent, CharSequence text) {
this.parentPattern = parent;
this.text = text;
// Allocate state storage
int parentGroupCount = Math.max(parent.capturingGroupCount, 10);
groups = new int[parentGroupCount * 2];
locals = new int[parent.localCount];
localsPos = new IntHashSet[parent.localTCNCount];
// Put fields into initial states
reset();
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 检索范围 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Sets the limits of this matcher's region. The region is the part of the
* input sequence that will be searched to find a match. Invoking this
* method resets the matcher, and then sets the region to start at the
* index specified by the {@code start} parameter and end at the
* index specified by the {@code end} parameter.
*
* <p>Depending on the transparency and anchoring being used (see
* {@link #useTransparentBounds(boolean) useTransparentBounds} and
* {@link #useAnchoringBounds(boolean) useAnchoringBounds}), certain
* constructs such as anchors may behave differently at or around the
* boundaries of the region.
*
* @param start The index to start searching at (inclusive)
* @param end The index to end searching at (exclusive)
*
* @return this matcher
*
* @throws IndexOutOfBoundsException If start or end is less than zero, if
* start is greater than the length of the input sequence, if
* end is greater than the length of the input sequence, or if
* start is greater than end.
* @since 1.5
*/
// 将matcher的检索范围设定在整个目标串的[start, end)之间
public Matcher region(int start, int end) {
if((start<0) || (start>getTextLength())) {
throw new IndexOutOfBoundsException("start");
}
if((end<0) || (end>getTextLength())) {
throw new IndexOutOfBoundsException("end");
}
if(start>end) {
throw new IndexOutOfBoundsException("start > end");
}
reset();
from = start;
to = end;
return this;
}
/**
* Reports the start index of this matcher's region. The
* searches this matcher conducts are limited to finding matches
* within {@link #regionStart() regionStart} (inclusive) and
* {@link #regionEnd() regionEnd} (exclusive).
*
* @return The starting point of this matcher's region
*
* @since 1.5
*/
// 返回当前检索范围的起点
public int regionStart() {
return from;
}
/**
* Reports the end index (exclusive) of this matcher's region.
* The searches this matcher conducts are limited to finding matches
* within {@link #regionStart() regionStart} (inclusive) and
* {@link #regionEnd() regionEnd} (exclusive).
*
* @return the ending point of this matcher's region
*
* @since 1.5
*/
// 返回当前检索范围的终点
public int regionEnd() {
return to;
}
/*▲ 检索范围 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 边界 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Sets the transparency of region bounds for this matcher.
*
* <p> Invoking this method with an argument of {@code true} will set this
* matcher to use <i>transparent</i> bounds. If the boolean
* argument is {@code false}, then <i>opaque</i> bounds will be used.
*
* <p> Using transparent bounds, the boundaries of this
* matcher's region are transparent to lookahead, lookbehind,
* and boundary matching constructs. Those constructs can see beyond the
* boundaries of the region to see if a match is appropriate.
*
* <p> Using opaque bounds, the boundaries of this matcher's
* region are opaque to lookahead, lookbehind, and boundary matching
* constructs that may try to see beyond them. Those constructs cannot
* look past the boundaries so they will fail to match anything outside
* of the region.
*
* <p> By default, a matcher uses opaque bounds.
*
* @param b a boolean indicating whether to use opaque or transparent
* regions
*
* @return this matcher
*
* @see java.util.regex.Matcher#hasTransparentBounds
* @since 1.5
*/
/*
* 设置是否使用透明边界(默认不使用透明边界,即使用不透明边界)
* 使用不透明边界时(默认),前瞻、后顾、边界匹配这些操作不会越过检索范围去匹配
* 换句话说,此时\b匹配到的边界未必是原文中真正的边界
*
* 例如使用"\bapple"去匹配"xapple"的[1, 6)范围:
* 如果使用了透明边界,可以看到a之前还有个x,无法匹配到满足条件的边界
* 如果使用了不透明边界,则索引1之前的x会被忽略,所以认为输入文本就是"apple",此时可以匹配到边界
*/
public Matcher useTransparentBounds(boolean b) {
transparentBounds = b;
return this;
}
/**
* Queries the transparency of region bounds for this matcher.
*
* <p> This method returns {@code true} if this matcher uses
* <i>transparent</i> bounds, {@code false} if it uses <i>opaque</i>
* bounds.
*
* <p> See {@link #useTransparentBounds(boolean) useTransparentBounds} for a
* description of transparent and opaque bounds.
*
* <p> By default, a matcher uses opaque region boundaries.
*
* @return {@code true} iff this matcher is using transparent bounds,
* {@code false} otherwise.
*
* @see java.util.regex.Matcher#useTransparentBounds(boolean)
* @since 1.5
*/
// 判断是否使用了透明边界(默认为false)
public boolean hasTransparentBounds() {
return transparentBounds;
}
/**
* Sets the anchoring of region bounds for this matcher.
*
* <p> Invoking this method with an argument of {@code true} will set this
* matcher to use <i>anchoring</i> bounds. If the boolean
* argument is {@code false}, then <i>non-anchoring</i> bounds will be
* used.
*
* <p> Using anchoring bounds, the boundaries of this
* matcher's region match anchors such as ^ and $.
*
* <p> Without anchoring bounds, the boundaries of this
* matcher's region will not match anchors such as ^ and $.
*
* <p> By default, a matcher uses anchoring region boundaries.
*
* @param b a boolean indicating whether or not to use anchoring bounds.
*
* @return this matcher
*
* @see java.util.regex.Matcher#hasAnchoringBounds
* @since 1.5
*/
/*
* 设置是否使用锚点边界(默认使用)
* 使用锚点边界时,行锚点^、\A、$、\Z、\z能匹配检索范围的边界,即检索范围不等于整个字符串
* 如果不使用锚点边界,则行锚点只能匹配检索范围内,整个目标字符串中符合规定的位置
*/
public Matcher useAnchoringBounds(boolean b) {
anchoringBounds = b;
return this;
}
/**
* Queries the anchoring of region bounds for this matcher.
*
* <p> This method returns {@code true} if this matcher uses
* <i>anchoring</i> bounds, {@code false} otherwise.
*
* <p> See {@link #useAnchoringBounds(boolean) useAnchoringBounds} for a
* description of anchoring bounds.
*
* <p> By default, a matcher uses anchoring region boundaries.
*
* @return {@code true} iff this matcher is using anchoring bounds,
* {@code false} otherwise.
*
* @see java.util.regex.Matcher#useAnchoringBounds(boolean)
* @since 1.5
*/
// 判断是否使用了锚点边界(默认为true)
public boolean hasAnchoringBounds() {
return anchoringBounds;
}
/*▲ 边界 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 捕获组 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the number of capturing groups in this matcher's pattern.
*
* <p> Group zero denotes the entire pattern by convention. It is not
* included in this count.
*
* <p> Any non-negative integer smaller than or equal to the value
* returned by this method is guaranteed to be a valid group index for
* this matcher. </p>
*
* @return The number of capturing groups in this matcher's pattern
*/
// 获取当前正则表达式中的捕获组数量(不考虑非捕获组)
public int groupCount() {
return parentPattern.capturingGroupCount - 1;
}
/**
* Returns the input subsequence matched by the previous match.
*
* <p> For a matcher <i>m</i> with input sequence <i>s</i>,
* the expressions <i>m.</i>{@code group()} and
* <i>s.</i>{@code substring(}<i>m.</i>{@code start(),} <i>m.</i>
* {@code end())} are equivalent. </p>
*
* <p> Note that some patterns, for example {@code a*}, match the empty
* string. This method will return the empty string when the pattern
* successfully matches the empty string in the input. </p>
*
* @return The (possibly empty) subsequence matched by the previous match,
* in string form
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
*/
// 获取整个正则表达式匹配到的目标串
public String group() {
return group(0);
}
/**
* Returns the input subsequence captured by the given group during the
* previous match operation.
*
* <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index
* <i>g</i>, the expressions <i>m.</i>{@code group(}<i>g</i>{@code )} and
* <i>s.</i>{@code substring(}<i>m.</i>{@code start(}<i>g</i>{@code
* ),} <i>m.</i>{@code end(}<i>g</i>{@code ))}
* are equivalent. </p>
*
* <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
* to right, starting at one. Group zero denotes the entire pattern, so
* the expression {@code m.group(0)} is equivalent to {@code m.group()}.
* </p>
*
* <p> If the match was successful but the group specified failed to match
* any part of the input sequence, then {@code null} is returned. Note
* that some groups, for example {@code (a*)}, match the empty string.
* This method will return the empty string when such a group successfully
* matches the empty string in the input. </p>
*
* @param group The index of a capturing group in this matcher's pattern
*
* @return The (possibly empty) subsequence captured by the group
* during the previous match, or {@code null} if the group
* failed to match part of the input
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IndexOutOfBoundsException If there is no capturing group in the pattern
* with the given index
*/
// 获取正则表达式中第group个捕获组匹配到的目标串(group为0时,效果同group())
public String group(int group) {
if(first<0) {
throw new IllegalStateException("No match found");
}
if(group<0 || group>groupCount()) {
throw new IndexOutOfBoundsException("No group " + group);
}
if((groups[group * 2] == -1) || (groups[group * 2 + 1] == -1)) {
return null;
}
return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
}
/**
* Returns the input subsequence captured by the given
* <a href="Pattern.html#groupname">named-capturing group</a> during the
* previous match operation.
*
* <p> If the match was successful but the group specified failed to match
* any part of the input sequence, then {@code null} is returned. Note
* that some groups, for example {@code (a*)}, match the empty string.
* This method will return the empty string when such a group successfully
* matches the empty string in the input. </p>
*
* @param name The name of a named-capturing group in this matcher's pattern
*
* @return The (possibly empty) subsequence captured by the named group
* during the previous match, or {@code null} if the group
* failed to match part of the input
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IllegalArgumentException If there is no capturing group in the pattern
* with the given name
* @since 1.7
*/
// 获取正则表达式中名称为name的捕获组匹配到的目标串
public String group(String name) {
int group = getMatchedGroupIndex(name);
if((groups[group * 2] == -1) || (groups[group * 2 + 1] == -1))
return null;
return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
}
/*▲ 捕获组 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 匹配 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Attempts to match the entire region against the pattern.
*
* <p> If the match succeeds then more information can be obtained via the
* {@code start}, {@code end}, and {@code group} methods. </p>
*
* @return {@code true} if, and only if, the entire region sequence
* matches this matcher's pattern
*/
/*
* 判断当前的正则表达式与当前的目标字符串是否完全匹配
* 该方法受检索范围的影响
*/
public boolean matches() {
return match(from, ENDANCHOR);
}
/**
* Attempts to match the input sequence, starting at the beginning of the
* region, against the pattern.
*
* <p> Like the {@link #matches matches} method, this method always starts
* at the beginning of the region; unlike that method, it does not
* require that the entire region be matched.
*
* <p> If the match succeeds then more information can be obtained via the
* {@code start}, {@code end}, and {@code group} methods. </p>
*
* @return {@code true} if, and only if, a prefix of the input
* sequence matches this matcher's pattern
*/
/*
* 判断当前的正则表达式能否在当前的目标字符串中找到匹配
* 与matches不同的是,该方法不要求正则表达式与目标字符串"完全匹配"
*/
public boolean lookingAt() {
return match(from, NOANCHOR);
}
/**
* Attempts to find the next subsequence of the input sequence that matches
* the pattern.
*
* <p> This method starts at the beginning of this matcher's region, or, if
* a previous invocation of the method was successful and the matcher has
* not since been reset, at the first character not matched by the previous
* match.
*
* <p> If the match succeeds then more information can be obtained via the
* {@code start}, {@code end}, and {@code group} methods. </p>
*
* @return {@code true} if, and only if, a subsequence of the input
* sequence matches this matcher's pattern
*/
/*
* 在目标字符串的当前检索范围中应用Matcher的正则表达式,返回的boolean值表示是否能找到匹配
* 如果多次调用,则每次都在上次的匹配位置之后尝试新的匹配
* 无参数的find只使用当前的检索范围
*/
public boolean find() {
int nextSearchIndex = last;
if(nextSearchIndex == first)
nextSearchIndex++;
// If next search starts before region, start it at region
if(nextSearchIndex<from)
nextSearchIndex = from;
// If next search starts beyond region then it fails
if(nextSearchIndex>to) {
for(int i = 0; i<groups.length; i++)
groups[i] = -1;
return false;
}
return search(nextSearchIndex);
}
/**
* Resets this matcher and then attempts to find the next subsequence of
* the input sequence that matches the pattern, starting at the specified
* index.
*
* <p> If the match succeeds then more information can be obtained via the
* {@code start}, {@code end}, and {@code group} methods, and subsequent
* invocations of the {@link #find()} method will start at the first
* character not matched by this match. </p>
*
* @param start the index to start searching for a match
*
* @return {@code true} if, and only if, a subsequence of the input
* sequence starting at the given index matches this matcher's
* pattern
*
* @throws IndexOutOfBoundsException If start is less than zero or if start is greater than the
* length of the input sequence.
*/
/*
* 该方法与无参数的find的不同之处在于:匹配会尝试从距离目标字符串开头ofset个字符的位置开始
* 如果ofset为负数或超出了目标字符串的长度,会抛出IndexoutofBoundsException异常
* 这种形式的find不会受当前检索范围的影响,而会把它设置为整个"目标字符串"
*/
public boolean find(int start) {
int limit = getTextLength();
if((start<0) || (start>limit))
throw new IndexOutOfBoundsException("Illegal start index");
reset();
return search(start);
}
/**
* Returns the start index of the previous match.
*
* @return The index of the first character matched
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
*/
// 获取上次匹配到的文本起点(包含)
public int start() {
if(first<0)
throw new IllegalStateException("No match available");
return first;
}
/**
* Returns the offset after the last character matched.
*
* @return The offset after the last character matched
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
*/
// 获取上次匹配到的文本终点(不包含)
public int end() {
if(first<0)
throw new IllegalStateException("No match available");
return last;
}
/**
* Returns the start index of the subsequence captured by the given group
* during the previous match operation.
*
* <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
* to right, starting at one. Group zero denotes the entire pattern, so
* the expression <i>m.</i>{@code start(0)} is equivalent to
* <i>m.</i>{@code start()}. </p>
*
* @param group The index of a capturing group in this matcher's pattern
*
* @return The index of the first character captured by the group,
* or {@code -1} if the match was successful but the group
* itself did not match anything
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IndexOutOfBoundsException If there is no capturing group in the pattern
* with the given index
*/
// 获取group捕获组中上次匹配到的文本起点(包含)
public int start(int group) {
if(first<0)
throw new IllegalStateException("No match available");
if(group<0 || group>groupCount())
throw new IndexOutOfBoundsException("No group " + group);
return groups[group * 2];
}
/**
* Returns the offset after the last character of the subsequence
* captured by the given group during the previous match operation.
*
* <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
* to right, starting at one. Group zero denotes the entire pattern, so
* the expression <i>m.</i>{@code end(0)} is equivalent to
* <i>m.</i>{@code end()}. </p>
*
* @param group The index of a capturing group in this matcher's pattern
*
* @return The offset after the last character captured by the group,
* or {@code -1} if the match was successful
* but the group itself did not match anything
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IndexOutOfBoundsException If there is no capturing group in the pattern
* with the given index
*/
// 获取group捕获组中上次匹配到的文本终点(不包含)
public int end(int group) {
if(first<0)
throw new IllegalStateException("No match available");
if(group<0 || group>groupCount())
throw new IndexOutOfBoundsException("No group " + group);
return groups[group * 2 + 1];
}
/**
* Returns the start index of the subsequence captured by the given
* <a href="Pattern.html#groupname">named-capturing group</a> during the
* previous match operation.
*
* @param name The name of a named-capturing group in this matcher's pattern
*
* @return The index of the first character captured by the group,
* or {@code -1} if the match was successful but the group
* itself did not match anything
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IllegalArgumentException If there is no capturing group in the pattern
* with the given name
* @since 1.8
*/
// 获取name捕获组中上次匹配到的文本起点(包含)
public int start(String name) {
return groups[getMatchedGroupIndex(name) * 2];
}
/**
* Returns the offset after the last character of the subsequence
* captured by the given <a href="Pattern.html#groupname">named-capturing
* group</a> during the previous match operation.
*
* @param name The name of a named-capturing group in this matcher's pattern
*
* @return The offset after the last character captured by the group,
* or {@code -1} if the match was successful
* but the group itself did not match anything
*
* @throws IllegalStateException If no match has yet been attempted,
* or if the previous match operation failed
* @throws IllegalArgumentException If there is no capturing group in the pattern
* with the given name
* @since 1.8
*/
// 获取name捕获组中上次匹配到的文本终点(不包含)
public int end(String name) {
return groups[getMatchedGroupIndex(name) * 2 + 1];
}
/*▲ 匹配 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 简单替换 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* replacement参数的预处理:
* 1> $1、$2之类的捕获组引用会被替换为对应位置的捕获组匹配到的目标文本
* 2> 如果$之后不是数字,会抛异常
* 3> $之后的数字,只会应用"有意义"的部分
* 4> 反斜杠用来转义后面的字符
*/
/**
* Replaces every subsequence of the input sequence that matches the
* pattern with the given replacement string.
*
* <p> This method first resets this matcher. It then scans the input
* sequence looking for matches of the pattern. Characters that are not
* part of any match are appended directly to the result string; each match
* is replaced in the result by the replacement string. The replacement
* string may contain references to captured subsequences as in the {@link
* #appendReplacement appendReplacement} method.
*
* <p> Note that backslashes ({@code \}) and dollar signs ({@code $}) in
* the replacement string may cause the results to be different than if it
* were being treated as a literal replacement string. Dollar signs may be
* treated as references to captured subsequences as described above, and
* backslashes are used to escape literal characters in the replacement
* string.
*
* <p> Given the regular expression {@code a*b}, the input
* {@code "aabfooaabfooabfoob"}, and the replacement string
* {@code "-"}, an invocation of this method on a matcher for that
* expression would yield the string {@code "-foo-foo-foo-"}.
*
* <p> Invoking this method changes this matcher's state. If the matcher
* is to be used in further matching operations then it should first be
* reset. </p>
*
* @param replacement The replacement string
*
* @return The string constructed by replacing each matching subsequence
* by the replacement string, substituting captured subsequences
* as needed
*/
// 使用replacement中的内容替换当前正则表达式匹配到的【所有】目标串,返回原字符串被替换后的副本(不受检索范围的限制)
public String replaceAll(String replacement) {
reset();
boolean result = find();
if(result) {
StringBuilder sb = new StringBuilder();
do {
appendReplacement(sb, replacement);
result = find();
} while(result);
appendTail(sb);
return sb.toString();
}
return text.toString();
}
/**
* Replaces the first subsequence of the input sequence that matches the
* pattern with the given replacement string.
*
* <p> This method first resets this matcher. It then scans the input
* sequence looking for a match of the pattern. Characters that are not
* part of the match are appended directly to the result string; the match
* is replaced in the result by the replacement string. The replacement
* string may contain references to captured subsequences as in the {@link
* #appendReplacement appendReplacement} method.
*
* <p>Note that backslashes ({@code \}) and dollar signs ({@code $}) in
* the replacement string may cause the results to be different than if it
* were being treated as a literal replacement string. Dollar signs may be
* treated as references to captured subsequences as described above, and
* backslashes are used to escape literal characters in the replacement
* string.
*
* <p> Given the regular expression {@code dog}, the input
* {@code "zzzdogzzzdogzzz"}, and the replacement string
* {@code "cat"}, an invocation of this method on a matcher for that
* expression would yield the string {@code "zzzcatzzzdogzzz"}. </p>
*
* <p> Invoking this method changes this matcher's state. If the matcher
* is to be used in further matching operations then it should first be
* reset. </p>
*
* @param replacement The replacement string
*
* @return The string constructed by replacing the first matching
* subsequence by the replacement string, substituting captured
* subsequences as needed
*/
// 使用replacement中的内容替换当前正则表达式匹配到的【首个】目标串,返回原字符串被替换后的副本(不受检索范围的限制)
public String replaceFirst(String replacement) {
if(replacement == null)
throw new NullPointerException("replacement");
reset();
if(!find())
return text.toString();
StringBuilder sb = new StringBuilder();
appendReplacement(sb, replacement);
appendTail(sb);
return sb.toString();
}
/**
* Replaces every subsequence of the input sequence that matches the
* pattern with the result of applying the given replacer function to the
* match result of this matcher corresponding to that subsequence.
* Exceptions thrown by the function are relayed to the caller.
*
* <p> This method first resets this matcher. It then scans the input
* sequence looking for matches of the pattern. Characters that are not
* part of any match are appended directly to the result string; each match
* is replaced in the result by the applying the replacer function that
* returns a replacement string. Each replacement string may contain
* references to captured subsequences as in the {@link #appendReplacement
* appendReplacement} method.
*
* <p> Note that backslashes ({@code \}) and dollar signs ({@code $}) in
* a replacement string may cause the results to be different than if it
* were being treated as a literal replacement string. Dollar signs may be
* treated as references to captured subsequences as described above, and
* backslashes are used to escape literal characters in the replacement
* string.
*
* <p> Given the regular expression {@code dog}, the input
* {@code "zzzdogzzzdogzzz"}, and the function
* {@code mr -> mr.group().toUpperCase()}, an invocation of this method on
* a matcher for that expression would yield the string
* {@code "zzzDOGzzzDOGzzz"}.
*
* <p> Invoking this method changes this matcher's state. If the matcher
* is to be used in further matching operations then it should first be
* reset. </p>
*
* <p> The replacer function should not modify this matcher's state during
* replacement. This method will, on a best-effort basis, throw a
* {@link java.util.ConcurrentModificationException} if such modification is
* detected.
*
* <p> The state of each match result passed to the replacer function is
* guaranteed to be constant only for the duration of the replacer function
* call and only if the replacer function does not modify this matcher's
* state.
*
* @param replacer The function to be applied to the match result of this matcher
* that returns a replacement string.
*
* @return The string constructed by replacing each matching subsequence
* with the result of applying the replacer function to that
* matched subsequence, substituting captured subsequences as
* needed.
*