Skip to content

Commit d2955b3

Browse files
committed
docs: simplify comment example
1 parent ef1675a commit d2955b3

File tree

1 file changed

+11
-19
lines changed

1 file changed

+11
-19
lines changed

README.md

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -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
```
4242
A 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 `-->`,
5247
so 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 `-->`.
5752
With `.not()` (aka. regex complement) this is easy:
5853

5954
```typescript
6055
import { 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

7264
With `.toRegExp()` we can convert back to a native JavaScript regex:
7365
```typescript
7466
commentRegex.toRegExp()
7567
```
7668
```
77-
/^(\/\*[^\*]*\*([^\*\/][^\*]*\*|\*)*\/)$/
69+
/^(<!-{2}(-{2}-*[^->]|-?[^-])*-{2}-*>)$/
7870
```
7971

8072
### Password Regex using Intersections

0 commit comments

Comments
 (0)