Does the following look like acceptable code to replace some escaped regex characters?
export function parseString(s: string): string {
let r : string;
if ( s[0] === 'r' || s[0] === 'R' ) {
r = s.substring(1); // no escape
} else {
r = s.substring(1, s.length - 1);
r= r.replace('\\n', '\n');
r= r.replace('\\r', '\r');
r= r.replace('\"', '"');
r= r.replace('\'', '\'');
r= r.replace('\\a', '\a');
r= r.replace('\\b', '\b');
r= r.replace('\\r', '\r');
r= r.replace('\\t', '\v');
r= r.replace('\\\\', '\\');
r= r.replace('\\?', '?');
r= r.replace('\\`', '\`');
const reg = /\\x../gi;
const regReseult = r.matchAll(reg);
let iter = regReseult.next();
while (!iter.done) {
r=r.replace(iter.value[0], escape_hex(iter.value[0]));
iter = regReseult.next();
}
}
return r;
}
function escape_hex( s: string ) : string {
let ss= s.toLowerCase();
if ( ss[0]!== '\\' || ss[1]!== 'x') {
throw new Error('Invalid hexadecimal escape sequence');
}
if ( ss.length !== 4) {
throw new Error('Invalid hexadecimal escape sequence');
}
const reg = /[0-9a-f][0-9a-f]/i;
if ( ss.match(reg) === null ) {
throw new Error('Invalid hexadecimal escape sequence');
}
ss= ss.replace('\\x', '0x');
return String.fromCharCode(_parseInt(ss));
}
Or, would a better pattern be to capture the various cases as a single regex such as \\[nr"'abrt\\?`] and then do a substitution based on the capture char? What might be the cleanest way to write the above function?
The goal of the above function is to parse a literal string as defined in BigQuery string-literals, which may accept a string in various forms such as "hello", 'hello', and r'hello\nthere'.
replaceonly replaces the first occurrence of the pattern if the pattern is a string. Are you sure this is working as you'd expect? \$\endgroup\$