Skip to content

Commit

Permalink
Fix dash escape at the end of the entire char class
Browse files Browse the repository at this point in the history
  • Loading branch information
hlysine committed Aug 20, 2023
1 parent 5a48f3b commit f7458e6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 27 deletions.
38 changes: 38 additions & 0 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,41 @@ export function wrapIfNeeded(regExp: string): string {
}
return `(?:${regExp})`;
}

export function escapeForCharClass(option: string): string {
if (option.startsWith('-')) {
option = '\\-' + option.substring(1);
}
let charEscaped = false;
for (let i = 0; i < option.length; i++) {
const char = option[i];
if (charEscaped) {
charEscaped = false;
} else if (char === '\\' || char === '-') {
if (i === option.length - 1) {
// escape characters at the end of the string
option = option.slice(0, -1) + '\\' + char;
break;
} else {
charEscaped = true;
}
} else if (char === ']' || char === '^') {
// escape this character
option = option.substring(0, i) + '\\' + option.substring(i);
charEscaped = true;
}
}
return option;
}

export function countTail(str: string, char: string): number {
let count = 0;
for (let i = str.length - 1; i >= 0; i--) {
if (str[i] === char) {
count++;
} else {
break;
}
}
return count;
}
35 changes: 8 additions & 27 deletions src/modifiers/CharacterClassModifier.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,5 @@
import { RegExpModifier } from '../types';

function escapeForCharClass(option: string): string {
if (option.startsWith('-')) {
option = '\\-' + option.substring(1);
}
let charEscaped = false;
for (let i = 0; i < option.length; i++) {
const char = option[i];
if (charEscaped) {
charEscaped = false;
} else if (char === '\\' || char === '-') {
if (i === option.length - 1) {
// escape backslash at the end of the string
option = option.substring(0, option.length - 1) + '\\' + char;
break;
} else {
charEscaped = true;
}
} else if (char === ']' || char === '^') {
// escape this character
option = option.substring(0, i) + '\\' + option.substring(i);
charEscaped = true;
}
}
return option;
}
import { countTail, escapeForCharClass } from '../helper';

export default class CharacterClassModifier implements RegExpModifier {
private readonly options: string[] = [];
Expand All @@ -47,7 +22,13 @@ export default class CharacterClassModifier implements RegExpModifier {
combined = '-' + combined.substring(2);
}
if (combined.endsWith('\\-')) {
combined = combined.substring(0, combined.length - 2) + '-';
const before = countTail(combined.slice(0, -2), '\\');
if (before % 2 === 0) {
combined = combined.slice(0, -2) + '-';
}
}
if (countTail(combined, '\\') % 2 === 1) {
combined += '\\';
}
return [`[${this.negative ? '^' : ''}${combined}]`, regExp];
}
Expand Down

0 comments on commit f7458e6

Please sign in to comment.