Skip to content

Commit 8e8c6cf

Browse files
committed
look behinds
- Closes #2
1 parent 31b8ed4 commit 8e8c6cf

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,15 @@ Similar to a capture(...), but won't keep the capture within the parentheses
7575
group('.|\\s') // -> (?:.|\\s)
7676
```
7777

78-
### `look.ahead.(positive|negative)`
78+
### `look.(ahead|behind).(positive|negative)`
7979

8080
Creates a [negative or positive look-ahead](https://www.stefanjudis.com/today-i-learned/the-complicated-syntax-of-lookaheads-in-javascript-regular-expressions/)
8181

8282
```javascript
83-
look.ahead.positive('Y') // -> '(?=y)'
83+
look.ahead.positive('Y') === look.ahead('Y') // -> '(?=y)'
8484
look.ahead.negative('Y') // -> '(?!y)'
85+
look.behind.positive('Y') === look.behind('Y') // -> '(?<=y)'
86+
look.behind.negative('Y') // -> '(?<!y)'
8587
```
8688

8789
#### `regex`

index.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ const group = v => (v && v.length ? `(${GROUP}${v})` : '')
3737

3838
const ALL = capture(or(ANY, WHITE_SPACE)) // matches any character or whitespace
3939

40-
const look = posOrNeg => text => `(?${posOrNeg ? '=' : '!'}${text})`
40+
const look = (posOrNeg, behindOrAhead) => text =>
41+
`(?${behindOrAhead ? '<' : ''}${posOrNeg ? '=' : '!'}${text})`
4142

4243
const regex = (...args) => new RegExp(...args)
4344

@@ -53,9 +54,13 @@ module.exports = exports.default = {
5354
capture,
5455
group,
5556
look: {
56-
ahead: Object.assign(look(true), {
57-
positive: look(true),
58-
negative: look(false)
57+
ahead: Object.assign(look(true, false), {
58+
positive: look(true, false),
59+
negative: look(false, false)
60+
}),
61+
behind: Object.assign(look(true, true), {
62+
positive: look(true, true),
63+
negative: look(false, true)
5964
})
6065
},
6166
matchers: {

index.spec.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,12 @@ describe('rexrex', () => {
5353
expect(repeat('8', 1, 2)).toEqual('8{1,2}')
5454
expect(repeat('8', 1, Infinity)).toEqual('8{1,}')
5555
})
56-
test('Look ahead', () => {
56+
test('Look ahead/behind', () => {
57+
expect(look.ahead('8')).toEqual('(?=8)')
5758
expect(look.ahead.positive('8')).toEqual('(?=8)')
5859
expect(look.ahead.negative('8')).toEqual('(?!8)')
60+
expect(look.behind('8')).toEqual('(?<=8)')
61+
expect(look.behind.positive('8')).toEqual('(?<=8)')
62+
expect(look.behind.negative('8')).toEqual('(?<!8)')
5963
})
6064
})

0 commit comments

Comments
 (0)