@@ -35,46 +35,38 @@ import { RB } from '@gruhn/regex-utils'
35
35
36
36
### Comment Regex using Complement
37
37
38
- How do you write a regex that matches comments like:
38
+ How do you write a regex that matches HTML comments like:
39
39
```
40
- /* This is a comment */
40
+ <!-- This is a comment -->
41
41
```
42
42
A straight forward attempt would be:
43
43
``` typescript
44
- \ / \ * . * \ * \ /
44
+ < ! -- . * -- >
45
45
```
46
- where
47
- - ` \/\* ` matches the start ` /* `
48
- - ` \*\/ ` matches the end ` */ `
49
- - and ` .* ` matches everything in between
50
-
51
- The problem is that ` .* ` also matches the end marker ` */ ` ,
46
+ The problem is that ` .* ` also matches the end marker ` --> ` ,
52
47
so this is also a match:
53
48
``` typescript
54
- /* This is a comment */ and this shouldn ' t be part of it * /
49
+ < ! -- This is a comment -- > and this shouldn ' t be part of it -- >
55
50
```
56
- We need to specify that the inner part can be anything except ` */ ` .
51
+ We need to specify that the inner part can be any string that does not contain ` --> ` .
57
52
With ` .not() ` (aka. regex complement) this is easy:
58
53
59
54
``` typescript
60
55
import { RB } from ' @gruhn/regex-utils'
61
56
62
- const commentInner = RB (/ ^ . * $ / ) // any string
63
- .concat (' */' ) // followed by comment end marker
64
- .concat (/ ^ . * $ / ) // followed by any string
65
- .not () // negate whole pattern
57
+ const strContainingCommentEnd = RB (/ . * -->. * / )
66
58
67
- const commentRegex = RB (' /* ' )
68
- .concat (commentInner )
69
- .concat (' */ ' )
59
+ const commentRegex = RB (' <!-- ' )
60
+ .concat (strContainingEndMarker . not () )
61
+ .concat (' --> ' )
70
62
```
71
63
72
64
With ` .toRegExp() ` we can convert back to a native JavaScript regex:
73
65
``` typescript
74
66
commentRegex .toRegExp ()
75
67
```
76
68
```
77
- /^(\/\ *[^\*]*\*([^\*\/][^\*]*\*|\*)*\/ )$/
69
+ /^(<!-{2}(-{2}- *[^->]|-?[^-])*-{2}-*> )$/
78
70
```
79
71
80
72
### Password Regex using Intersections
0 commit comments