@@ -35,46 +35,38 @@ import { RB } from '@gruhn/regex-utils'
3535
3636### Comment Regex using Complement
3737
38- How do you write a regex that matches comments like:
38+ How do you write a regex that matches HTML comments like:
3939```
40- /* This is a comment */
40+ <!-- This is a comment -->
4141```
4242A straight forward attempt would be:
4343``` typescript
44- \ / \ * . * \ * \ /
44+ < ! -- . * -- >
4545```
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 ` --> ` ,
5247so this is also a match:
5348``` 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 -- >
5550```
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 ` --> ` .
5752With ` .not() ` (aka. regex complement) this is easy:
5853
5954``` typescript
6055import { RB } from ' @gruhn/regex-utils'
6156
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 (/ . * -->. * / )
6658
67- const commentRegex = RB (' /* ' )
68- .concat (commentInner )
69- .concat (' */ ' )
59+ const commentRegex = RB (' <!-- ' )
60+ .concat (strContainingEndMarker . not () )
61+ .concat (' --> ' )
7062```
7163
7264With ` .toRegExp() ` we can convert back to a native JavaScript regex:
7365``` typescript
7466commentRegex .toRegExp ()
7567```
7668```
77- /^(\/\ *[^\*]*\*([^\*\/][^\*]*\*|\*)*\/ )$/
69+ /^(<!-{2}(-{2}- *[^->]|-?[^-])*-{2}-*> )$/
7870```
7971
8072### Password Regex using Intersections
0 commit comments