Skip to content

Commit 9e24f8a

Browse files
committed
Automatically anchor regular expressions
1 parent af6769e commit 9e24f8a

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/constructors.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,13 @@ export const nothing: ParserWhichAlwaysSucceeds<undefined> = input =>
3636
output: undefined,
3737
})
3838

39-
export const regularExpression =
40-
(pattern: RegExp): Parser<string> =>
41-
input => {
42-
const match = pattern.exec(input)
43-
return match === null || match.index !== 0
39+
export const regularExpression = (pattern: RegExp): Parser<string> => {
40+
const patternAnchoredToStartOfString = pattern.source.startsWith('^')
41+
? pattern
42+
: new RegExp(`^${pattern.source}`, pattern.flags)
43+
return input => {
44+
const match = patternAnchoredToStartOfString.exec(input)
45+
return match === null
4446
? either.makeLeft({
4547
input,
4648
message: 'input did not match regular expression',
@@ -50,3 +52,4 @@ export const regularExpression =
5052
output: match[0],
5153
})
5254
}
55+
}

0 commit comments

Comments
 (0)