-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRegExp.dib
963 lines (633 loc) · 23.9 KB
/
RegExp.dib
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
#!meta
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
#!markdown
<br>
<div style="text-align: center;">
<pre style="display: inline-block; text-align: left;">
_____ ______ __ __
| __ \ | ____| / / \ \
| |__) |___ __ _| |__ __ __ | | _ __ | |
| _ // _ \/ _` | __| \ \/ / | || '_ \| |
| | \ \ __/ (_| | |____ > < | || |_) | |
|_| \_\___|\__, |______/_/\_\ | || .__/| |
__/ | \_\ | /_/
|___/ |_|
</pre>
</div>
<br>
<br>
#!markdown
<div style="text-align: center;">
<img src="./welcome-to-regex-hell.png" alt="Welcome to regex hell Meme" style="height: 550px;">
</div>
#!markdown
---
#!markdown
# Regex language feature comparison
<img src="./RegexJS.png" alt="Regex Table" style="width: 100%">
> This image is compiled from [Wikipedia](https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines#Language_features) 2021
So lets focus on JavaScript RegEx
#!markdown
----
# What will we talk about today?
- **Basic concepts (Part 1)**
- `|` OR statement
- `( )` Grouping
- **Assertions**
- `\N`
- `^` & `$`
- `[abc]` , `[^xyz]` & `[a-z]`
- **Quantifiers**
- `?` & `*`
- `+`
- `x{n}`, `x{n,}` , `x{,m}` & `x{n,m}`
- `x*?`, `x{n,m}?`
- Character classes (Part 2)
- `.`
- `\w` & `\W`
- `\d` & `\D`
- `\s` & `\S`
- `\t` , `\r` , `\n` , `\v` , `\f` , `\0`
- `\xHH` , `\uHHHH` , `\u{HHHH}` or `\u{HHHHH}`
- RegExp flags
- g = **g***lobal*
- i = *case* **i***nsensitive*
- m = **m***ultiline*
- s = **s***ingle line*
- u = **u***nicode* `\p{X}` & `\P{X}`
- y = *stick***y**
- d = generate indices for substring matches
- The hard part of RegExp
- `[ ]` or `( )`
- Utilizing (named) groups in code
- difference between exec and match
```JavaScript
const raw = /pattern/flags
const cls = new RegExp('pattern', 'flags');
const cls = new RegExp(/pattern/, 'flags');
```
<br>
----
#!markdown
# Basic Consepts
## OR statement
#!javascript
const regex = /gray|grey/
const mkay = regex.test('mkay') // false
const gray = regex.test('gray')
const grey = regex.test('grey')
console.log(`mkay: ${mkay} \ngray: ${gray} \ngrey: ${grey}`)
#!markdown
## Grouping
#!javascript
const regex = /gr(a|e)y/
const mkay = regex.test('mkay')
const gray = regex.test('gray')
const grey = regex.test('grey')
console.log(`mkay: ${mkay} \ngray: ${gray} \ngrey: ${grey}`)
#!markdown
<br>
<br>
---
#!markdown
# Assertions
An Assertion in Regular Expression is **when a match is possible in some way**
### \N
#!javascript
const regexA = /\040/
const regexB = / /
const testA = regexA.test('Hello there')
const testB = regexB.test('Hello there')
console.log(`testA: ${testA}\ntestB: ${testB}`)
#!markdown
### ^ & $
#!javascript
const start = /^start/
const end = /end$/
const startA = start.test('start end')
const startB = start.test(' start end ')
const endA = end.test('start end\n end')
const endB = end.test(' start end ')
console.log(`startA: ${startA} startB: ${startB}\n- endA: ${endA} - endB: ${endB}`)
#!markdown
---
#!markdown
### [abc] Character set
#!javascript
const regex = /[eaiou]/g
const response = 'You shall not pass!'.match(regex)
console.log(response)
#!markdown
### [^xyz] Negated set
#!javascript
const regex = /[^eaiou]/g
const response = 'You shall not pass!'.match(regex)
console.log(response)
#!markdown
### [a-z] Range
#!javascript
const regex = /[A-Za-z]/g
const response = 'abcdef]gHIJKLMN'.match(regex)
console.log(response)
#!markdown
<br>
---
#!markdown
# Quantifiers
A quantifier after an element (such as a token, character, or group) specifies how many times the preceding element is allowed to repeat.
The most common quantifiers are the question mark ?, the asterisk * (derived from the Kleene star), and the plus sign + (Kleene plus).
### ? - 0 or 1
#!javascript
const regex = /^colou?r$/
const colouur = regex.test('colouur')
const colour = regex.test('colour')
const color = regex.test('color')
console.log(`colouur: ${colouur} \ncolour: ${colour} \ncolor: ${color}`)
#!markdown
### * - 0 or more
#!javascript
const regex = /^colou*r$/
const colouur = regex.test('colouur')
const colour = regex.test('colour')
const color = regex.test('color')
console.log(`colouur: ${colouur} \ncolour: ${colour} \ncolor: ${color}`)
#!markdown
---
#!markdown
### + - 1 or more
#!javascript
const regex = /^colou+r$/
const colouur = regex.test('colouur')
const colour = regex.test('colour')
const color = regex.test('color')
console.log(`colouur: ${colouur} \ncolour: ${colour} \ncolor: ${color}`)
#!markdown
### X{n} - N amount
#!javascript
const regexA = /^colou{1}r$/
const regexB = /^colou{2}r$/
const colouurA = regexA.test('colouur')
const colourA = regexA.test('colour')
const colorA = regexA.test('color')
const colouurB = regexB.test('colouur')
const colourB = regexB.test('colour')
const colorB = regexB.test('color')
console.log(`- colouurA: ${colouurA} - colourA: ${colourA} - colorA: ${colorA}\n- colouurB: ${colouurB} - colourB: ${colourB} - colorB: ${colorB}`)
#!markdown
<br>
<br>
---
#!markdown
### X{n,} minimum that X needs to be found
`n` needs to be positive
`+` is the same as `X{1,}`
`*` is the same as `X{0,}`
`?` is the same as `X{0,1}`
#!javascript
const regex = /^colou{2,}r$/
const colouuur = regex.test('colouuur')
const colouur = regex.test('colouur')
const colour = regex.test('colour')
console.log(`colouuur: ${colouuur} - colouur: ${colouur} - colour: ${colour}`)
#!markdown
### X{n,m} minimum and maximum
`m` always needs to be bigger then what is before the `,`
`?` is the same as `X{0,1}`
> Some browsers accept `X{,1}` to be the same as `X{0,1}`
#!javascript
const regex = /^colou{2,3}r$/
const colouuuur = regex.test('colouuuur')
const colouuur = regex.test('colouuur')
const colouur = regex.test('colouur')
const colour = regex.test('colour')
console.log(`colouuuur: ${colouuuur} - colouur: ${colouur} \ncolouuur: ${colouuur} - colour: ${colour}`)
#!markdown
---
### X+? and X{n,m}? - Lazy quantifiers
So all the quantifiers that we just went over can be made lazy with an additional ?
By default are the expressions greedy.
Yes `x??` is possible.
No I have not found a use case for `x??`
#!javascript
// Also named a greedy quantifier
const regexGreedy = /"(.*)"/g
const quotes = `Is it "You shall not pass!" or is it "You cannot pass!"`
const responseGreedy = quotes.match(regexGreedy)
// Also named a lazy quantifier due to the ?
const regexLazy = /"(.*?)"/g
const responseLazy = quotes.match(regexLazy)
console.log(`Greedy: [${responseGreedy}] \nLazy: [${responseLazy}]`)
#!markdown
<div style="text-align: center;">
<img src="./toy-story-greed.jpeg" alt="Toy story greed Meme" style="height: 350px;">
</div>
---
#!markdown
<br>
<div style="text-align: center;">
<pre style="display: inline-block; text-align: left;">
______ _ __ _____ _ __
| ____| | | / _| | __ \ | | /_ |
| |__ _ __ __| | ___ | |_ | |__) |_ _ _ __| |_ | |
| __| | '_ \ / _` | / _ \| _| | ___/ _` | '__| __| | |
| |____| | | | (_| | | (_) | | | | | (_| | | | |_ | |
|______|_| |_|\__,_| \___/|_| |_| \__,_|_| \__| |_|
</pre>
</div>
<br>
<br>
#!markdown
<div style="text-align: center;">
<img src="./yer-a-regex-wizard.jpg" alt="Yer a regex wizard Meme" style="height: 550px;">
</div>
<br>
---
#!markdown
<br>
<div style="text-align: center;">
<pre style="display: inline-block; text-align: left;">
_____ ______ __ __ _____ _ ___
| __ \ | ____| / / \ \ | __ \ | | |__ \
| |__) |___ __ _| |__ __ __ | | _ __ | | | |__) |_ _ _ __| |_ ) |
| _ // _ \/ _` | __| \ \/ / | || '_ \| | | ___/ _` | '__| __| / /
| | \ \ __/ (_| | |____ > < | || |_) | | | | | (_| | | | |_ / /_
|_| \_\___|\__, |______/_/\_\ | || .__/| | |_| \__,_|_| \__| |____|
__/ | \_\ | /_/
|___/ |_|
</pre>
</div>
<br>
<br>
#!markdown
<div style="text-align: center;">
<img src="./how-to-catex.webp" alt="How to Catex Meme" style="height: 525px;">
</div>
#!markdown
----
# What will we talk about today?
- Basic concepts (Part 1)
- `|` OR statement
- `( )` Grouping
- Assertions
- `\N`
- `^` & `$`
- `[abc]` , `[^xyz]` & `[a-z]`
- Quantifiers
- `?` & `*`
- `+`
- `x{n}`, `x{n,}` , `x{,m}` & `x{n,m}`
- `x*?`, `x{n,m}?`
- **Character classes (Part 2)**
- `.`
- `\w` & `\W`
- `\d` & `\D`
- `\s` & `\S`
- `\t` , `\r` , `\n` , `\v` , `\f` , `\0`
- `\xHH` , `\uHHHH` , `\u{HHHH}` or `\u{HHHHH}`
- **RegExp flags**
- g = **g***lobal*
- i = *case* **i***nsensitive*
- m = **m***ultiline*
- s = **s***ingle line*
- u = **u***nicode* `\p{X}` & `\P{X}`
- y = *stick***y**
- d = generate indices for substring matches
- **The hard part of RegExp**
- ` [ ] ` or ` ( ) `
- Utilizing (named) groups in code
- difference between exec and match
```JavaScript
const raw = /pattern/flags
const cls = new RegExp('pattern', 'flags');
const cls = new RegExp(/pattern/, 'flags');
```
----
#!markdown
# Character classes
**Character classes** are one of the most commonly used features of **regular expressions**.
A character class allows you to match any symbol from a certain character set. A character class is also called a character set
### . - Yes that is a character class
#!javascript
const regex = /.+/
const mkay = regex.test('mkay')
const gray = regex.test('gray')
const grey = regex.test('grey')
console.log(`mkay: ${mkay} \ngray: ${gray} \ngrey: ${grey}`)
#!markdown
<div style="text-align: center;">
<img src="./first-the-dot.jpg" alt="First the dot Meme" Meme" style="height: 425px;">
</div>
#!markdown
<br>
----
### \w & \W
#!javascript
const regexA = /\w+/g
const regexB = /[a-zA-Z0-9_]+/g
const responseA = 'You shall not pass!'.match(regexA)
const responseB = 'You shall not pass!'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!javascript
const regexA = /\W+/g
const regexB = /[^a-zA-Z0-9_]/g
const responseA = 'You shall not pass!'.match(regexA)
const responseB = 'You shall not pass!'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!markdown
<br>
<br>
----
### \d & \D
#!javascript
const regexA = /\d/g
const regexB = /[0-9]/g
const responseA = 'I can only count to 4. 1, 2, 5, 4. Me count so poor'.match(regexA)
const responseB = 'I can only count to 4. 1, 2, 5, 4. Me count so poor'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!javascript
const regexA = /\D/g
const regexB = /[^0-9]/g
const responseA = 'I can only count to 4. 1, 2, 5, 4. Me count so poor'.match(regexA)
const responseB = 'I can only count to 4. 1, 2, 5, 4. Me count so poor'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!markdown
----
### \s & \S
#!javascript
const regexA = /\s/g
const regexB = /[ \t\n]/g
const responseA = 'You shall not pass!'.match(regexA)
const responseB = 'You shall not pass!'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!javascript
const regexA = /\S/g
const regexB = /[^ \t\n]/g
const responseA = 'You shall not pass!'.match(regexA)
const responseB = 'You shall not pass!'.match(regexB)
console.log('Response A: ', responseA)
console.log('Response B: ', responseB)
#!markdown
<br>
<br>
----
### \t, \r, \n
#!javascript
const regexA = /\t/
const regexB = / / // tab token
const responseA = ' Tabs vs spaces'.match(regexA)
const responseB = ' Tabs vs spaces'.match(regexB)
console.log(responseA)
console.log(responseB) // note the rendered \t
#!javascript
const regexA = /\r\n/ // known as CRLF used in Windows (can be set by your code editor)
const regexB = /\n/ // known as LF is used in Unix, Unix only uses LF as line breaks.
const regexC = /\r/ // known as CR used in the old MacOS (pre-OSX MacIntosh)
const textA = '\r\n'
const textB = '\n'
const textC = '\r'
const resultA = [regexA.test(textA), regexA.test(textB), regexA.test(textC)]
const resultB = [regexB.test(textA), regexB.test(textB), regexB.test(textC)]
const resultC = [regexC.test(textA), regexC.test(textB), regexC.test(textC)]
console.log(['\r\n', '\n', '\r'])
console.log(resultA)
console.log(resultB)
console.log(resultC)
#!markdown
----
### \0, \f, \v
#!javascript
// Machtes a null caracter
const nullRegex = /\0/
// A hidden white space
const whiteSpaceR = /\f/ // the readable version
const whiteSpaceH = // // my editor makes it look like this
const vSimple = /\v/ // matches unicode vertical whitespace, considered a character class by the PCRE engine
const vFull = /[\n\r\f\u000B\u0085\u2028\u2029]/ // or its represented like this
const verticalTabR = /\u000B/
const verticalTabH = // // the vertical tab
const lineSeparatorR = /\u0085/
const lineSeparatorH = /
/ // the line separator
// The following info will VS Code show
// The character U+2028 "
" and U+2029 "
" could be confused with the character U+0020, which is more common in source code. Adjust settings
const weirdSpace0R = /\u2028/
const weirdSpace0H = /
/
const weirdSpace1R = /\u2029/
const weirdSpace1H = /
/
#!markdown
[Stack**overflow**](https://stackoverflow.com/a/9168133/7185314)
> it's a feature of the JavaScript language, documented in the ECMAScript standard (3rd edition section 7.3),
> that the U+2028 and U+2029 characters count as line endings.
> Consequently a JavaScript parser will treat any unencoded U+2028/9 character in the same way as a newline.
> Since you can't put a newline inside a string literal, you get a syntax error.
>
> This is an unfortunate oversight in the design of JSON: it is not actually a proper subset of JavaScript.
> Raw U+2028/9 characters are valid in string literals in JSON,
> and will be accepted by JSON.parse, but not so in JavaScript itself.
>
> Hence it is only safe to generate JavaScript code using a JSON parser if you're sure it explicitly \u-escapes those characters.
> Some do, some don't; many \u-escape all non-ASCII characters, which avoids the problem.
---
#!markdown
### \xHH , \uHHHH , \u{HHHH} or \u{HHHHH}
As shown in the **\0, \f, \v** part above we have seen some use of the \uHHHH
***WARNING*** The use of \u{HHHH} or \u{HHHHH} might not be supported in all browsers / js engines
#!javascript
const regexA = /\u000B/ // \uHHHH matches 4 hexadecimal digits this one is used on previouse page as well
const regexB = /\x0B/ // \xHH matches 2 hexadecimal digits
const regexC = /\u{000B}/u // \u{HHHH} matches 4 hexadecimal digits when unicode flag is used
const regexD = /\u{0000B}/u // \u{HHHHH} matches Surrogates and Supplementary characters in the hexadecimal
const text = ''
resultA = regexA.test(text)
resultB = regexB.test(text)
resultC = regexC.test(text)
resultD = regexD.test(text)
console.log(`\\u000B: ${resultA} \n\\x0B: ${resultB} \n\\u{000B}: ${resultC} \n\\u{0000B}: ${resultD}`)
#!markdown
Oracle:
> To support supplementary characters without changing the char primitive data type and causing incompatibility with previous Java programs, supplementary characters are defined by a pair of code point values that are called surrogates. The first code point is from the high surrogates range of U+D800 to U+DBFF, and the second code point is from the low surrogates range of U+DC00 to U+DFFF. For example, the Deseret character LONG I, U+10400, is defined with this pair of surrogate values: U+D801 and U+DC00.
Windows:
> Windows applications normally use UTF-16 to represent Unicode character data. The use of 16 bits allows direct representation of 65,536 unique characters, but this Basic Multilingual Plane (BMP) is not nearly enough to cover all the symbols used in human languages. Unicode version 4.1 includes over 97,000 characters, with over 70,000 characters for Chinese alone.
>
> The Unicode standard has established 16 additional "planes" of characters, each the same size as the BMP. Naturally, most code points beyond the BMP do not yet have characters assigned to them, but definition of the planes gives Unicode the potential to define 1,114,112 characters (that is, 216 * 17 characters) within the code point range U+0000 to U+10FFFF. For UTF-16 to represent this larger set of characters, the Unicode Standard defines "supplementary characters".
#!markdown
----
# Flags
Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching.
These flags can be used separately or together in any order,
and are included as part of the regular expression.
#!javascript
const raw = /pattern/flags
const cls = new RegExp('pattern', 'flags');
const cls = new RegExp(/pattern/, 'flags');
#!markdown
## Flags we have seen here
- Global
- Unicode
What do we remember of them?
<div style="text-align: center;">
<img src="./regex-math.png" alt="Regex math Meme" style="height: 300px;">
</div>
<br>
<br>
----
#### /g - Continues to find more matches after the first one
#!javascript
const regex1 = new RegExp('foo', 'g');
const regex2 = new RegExp('bar', '');
// expected output: regex1: true regex2: false
console.log(`Example1: regex1: ${regex1.global} regex2: ${regex2.global}`);
const regexp1 = /t(e)(st(\d?))/g; // \d matches numbers
const regexp2 = /t(e)(st(\d?))/;
const str = 'test1test2';
const arrayAll = [...str.matchAll(regexp1)];
const arrayMatchA = str.match(regexp1)
const arrayMatchB = str.match(regexp2)
console.log('Example2')
console.log(arrayAll[0]);
// expected output: arrayAll ["test1", "e", "st1", "1"]
console.log(arrayAll[1]);
// expected output: arrayAll ["test2", "e", "st2", "2"]
console.log(arrayMatchA);
// expected output: arrayMatchA ["test1", "test1"]
console.log(arrayMatchB);
// expected output: arrayMatchB ["test1", "e", "st1", "1"]
#!markdown
----
#### /u - Having the power of unicode's!
#!javascript
const regex1 = /\p{Emoji_Presentation}/g
const regex2 = /\p{Emoji_Presentation}/gu
const regex3 = /\p{Script_Extensions=Armenian}+/gu
const regex4 = /\P{Script_Extensions=Armenian}+/gu
const regex5 = /\u{000B}/u // \u{HHHH} matches 4 hexadecimal digits when unicode flag is used
const regex6 = /\u{0000B}/u // \u{HHHHH} matches Surrogates and Supplementary characters in the hexadecimal
const str = 'զվարճանք is the word "fun" in Armenian 👌 '
console.log(str.match(regex1))
console.log(str.match(regex2))
console.log(str.match(regex3))
console.log(str.match(regex4))
console.log(str.match(regex4))
console.log(str.match(regex4))
#!markdown
##### Other handy modifiers from \p
`/\p{Lu}/` Matches an uppercase letter that has an lowercase variant
`/\p{Ll}/` Matches a lowercase letter that has an uppercase variant
You do not need to use the /u flag on those modifiers.
----
#### /i /m /s
#!javascript
const regexI1 = /NOTE/i // case Insensitve flag
const regexI2 = /NOTE/
const test1 = regexI1.test('note')
const test2 = regexI2.test('note')
console.log(`Case insensitve: ${test1} expected: true \nCase sensitve: ${test2} expected: false`)
#!javascript
const regexM1 = /^foo/m // Multiline flag
const regexM2 = /^foo/
const test1 = regexM1.test('\nfoo') // Regex sees everly line as start of matching
const test2 = regexM2.test('\nfoo') // Regex sees \n as start of matching
console.log(`Multiline on: ${test1} expected: true \nMultiline off: ${test2} expected: false`)
#!javascript
const regexS1 = /bar.example/s // Single line flag
const regexS2 = /bar.example/
const str = 'bar\nexample foo example' // multi line string
console.log(`Test on new line: ${regexS1.test(str)} | expected: true \nTest on new line: ${regexS2.test(str)} | expected: false`)
#!markdown
----
#### /y
Perform a "stick**y**" search that matches starting at the current position in the target string
#!javascript
const regex = /^foo/my
regex.lastIndex = 2;
const res1 = regex.test('..foo')
regex.lastIndex = 2;
const res2 = regex.test('.\nfoo')
console.log(` "..foo": ${res1} \n ".\\nfoo": ${res2} `)
#!markdown
#### /d
in**d**ices. The JavaScript regex engine now returns the indices at which the regex matched in the subject string.
#!javascript
const regexD1 = /foo/gd // Gives string position of your matches
const regexD2 = /foo/g
const str = 'foo bar foo'
console.log(regexD1.exec(str).indices[0])
console.log(regexD1.exec(str).indices[0])
console.log(regexD2.exec(str).indices)
#!markdown
----
## The hard part of RegExp
#### ( ) and [ ]
#!javascript
const regexA = /gr(a|e)y/
const regexB = /gr[ae]y/
const mkayA = regexA.test('mkay')
const grayA = regexA.test('gray')
const greyA = regexA.test('grey')
const mkayB = regexB.test('mkay')
const grayB = regexB.test('gray')
const greyB = regexB.test('grey')
console.log(`mkayA: ${mkayA} | mkayB: ${mkayB} \ngrayA: ${grayA} | grayB: ${grayB} \ngreyA: ${greyA} | greyB: ${greyB}`)
#!markdown
#### Utilizing (named) groups in code
> Comment and uncomment to see the difference with named groups and without
#!javascript
const imageDescription = 'This image has a resolution of 1440x900 pixels.'
// const regexpSize = /(([0-9]+)x([0-9]+)) pixels/ // before named groups where a thing 🧠
const regexpSize = /(?<resolution>(?<width>[0-9]+)x(?<height>[0-9]+)) pixels/ // adding named groups making it readable ✨
const result = imageDescription.match(regexpSize)
const [fullMatch, group1, group2, group3] = result
const { resolution, width, height } = result.groups
console.log(`Group - Width: ${group2} / Height: ${group3}. Resolution: ${group1}. Full match: ${fullMatch}`)
// expected output: "Group - Width: 1440 / Height: 900. Resolution: 1440x900. Full match: 1440x900 pixels"
console.log(`Named - Width: ${width} / Height: ${height}. Resolution: ${resolution}. Full match: ${fullMatch}`)
// expected output: "Named - Width: 1440 / Height: 900. Resolution: 1440x900. Full match: 1440x900 pixels"
#!markdown
---
#### Difference between exec and match
`string.match(regexp)`
does not update the state of the regexp
`regexp.exec(string)`
does update the state of the regexp
example modified from [mdn web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
#!javascript
const regexp = RegExp('foo*', 'g');
const string = 'table football, foosball';
let array1;
let array2;
array1 = string.match(regexp)
console.log(`Found ${array1[0]}. Next starts at ${regexp.lastIndex}.`);
// Expected output: "Found foo. Next starts at 0."
while ((array2 = regexp.exec(string)) !== null) {
console.log(`Found ${array2[0]}. Next starts at ${regexp.lastIndex}.`);
// Expected output: "Found foo. Next starts at 9."
// Expected output: "Found foo. Next starts at 19."
}
array1 = string.match(regexp) // does not care of the regexp state
console.log(`Found ${array1[0]}. Next starts at ${regexp.lastIndex}.`);
// Expected output: "Found foo. Next starts at 0."
#!markdown
----
<br>
<div style="text-align: center;">
<pre style="display: inline-block; text-align: left;">
______ _ __ _____ __ __
| ____| | | / _| | __ \ / / \ \
| |__ _ __ __| | ___ | |_ | |__) |___ __ _ _____ __ | | _ __ | |
| __| | '_ \ / _` | / _ \| _| | _ // _ \/ _` |/ _ \ \/ / | || '_ \| |
| |____| | | | (_| | | (_) | | | | \ \ __/ (_| | __/> < | || |_) | |
|______|_| |_|\__,_| \___/|_| |_| \_\___|\__, |\___/_/\_\ | || .__/| |
__/ | \_\ | /_/
|___/ |_|
</pre>
</div>
<br>
<br>
<div style="text-align: center;">
<img src="./I-know-regex.png" alt="I know regex Meme" style="height: 600px;">
</div>
----