|
1 | 1 | package com.github.h0tk3y.betterParse.lexer |
2 | 2 |
|
3 | | -import kotlin.js.RegExp |
4 | | - |
5 | 3 | public actual class RegexToken : Token { |
6 | 4 | private val pattern: String |
7 | 5 | private val regex: Regex |
8 | 6 |
|
9 | | - /** |
10 | | - * To ensure that the [regex] will only match its pattern from the index where it is called on |
11 | | - * with Regex.find(input, startIndex), set the JS RegExp flag 'y', which makes the RegExp |
12 | | - * 'sticky'. See: https://javascript.info/regexp-sticky |
13 | | - */ |
14 | | - private fun preprocessRegex(regex: Regex) { |
15 | | - val possibleNames = listOf("nativePattern_1", "nativePattern_0", "_nativePattern") |
16 | | - for (name in possibleNames) { |
17 | | - val r = regex.asDynamic()[name] |
18 | | - if (jsTypeOf(r) !== "undefined" && r !== null) { |
19 | | - val src = r.source as String |
20 | | - val flags = r.flags as String + if (r.sticky as Boolean) "" else "y" |
21 | | - regex.asDynamic()[name] = RegExp(src, flags) |
22 | | - break |
23 | | - } |
24 | | - } |
25 | | - } |
26 | | - |
27 | 7 | public actual constructor( |
28 | 8 | name: String?, |
29 | 9 | patternString: String, |
30 | 10 | ignored: Boolean |
31 | 11 | ) : super(name, ignored) { |
32 | 12 | pattern = patternString |
33 | 13 | regex = pattern.toRegex() |
34 | | - preprocessRegex(regex) |
35 | 14 | } |
36 | 15 |
|
37 | 16 | public actual constructor(name: String?, regex: Regex, ignored: Boolean) : super(name, ignored) { |
38 | 17 | pattern = regex.pattern |
39 | 18 | this.regex = regex |
40 | | - preprocessRegex(regex) |
41 | 19 | } |
42 | 20 |
|
43 | 21 | override actual fun match(input: CharSequence, fromIndex: Int): Int = |
44 | 22 | regex.find(input, fromIndex)?.range?.let { |
45 | | - val length = it.last - it.first + 1 |
46 | | - length |
| 23 | + if (it.first == fromIndex) { |
| 24 | + val length = it.last - it.first + 1 |
| 25 | + length |
| 26 | + } else 0 |
47 | 27 | } ?: 0 |
48 | 28 |
|
49 | 29 | override fun toString(): String = "${name ?: ""} [$pattern]" + if (ignored) " [ignorable]" else "" |
|
0 commit comments