【发布时间】:2021-10-20 20:37:39
【问题描述】:
我正在尝试在 Javasacript 中提取 JPA 命名参数。而这就是我能想到的算法
const notStrRegex = /(?<![\S"'])([^"'\s]+)(?![\S"'])/gm
const namedParamCharsRegex = /[a-zA-Z0-9_]/;
/**
* @returns array of named parameters which,
* 1. always begins with :
* 2. the remaining characters is guranteed to be following {@link namedParamCharsRegex}
*
* @example
* 1. "select * from a where id = :myId3;" -> [':myId3']
* 2. "to_timestamp_tz(:FROM_DATE, 'YYYY-MM-DD\"T\"HH24:MI:SS')" -> [':FROM_DATE']
* 3. "TO_CHAR(ep.CHANGEDT,'yyyy=mm-dd hh24:mi:ss')" -> []
*/
export function extractNamedParam(query: string): string[] {
return (query.match(notStrRegex) ?? [])
.filter((word) => word.includes(':'))
.map((splittedWord) => splittedWord.substring(splittedWord.indexOf(':')))
.filter((splittedWord) => splittedWord.length > 1) // ignore ":"
.map((word) => {
// i starts from 1 because word[0] is :
for (let i = 1; i < word.length; i++) {
const isAlphaNum = namedParamCharsRegex.test(word[i]);
if (!isAlphaNum) return word.substring(0, i);
}
return word;
});
}
我受到了解决方案的启发 https://stackoverflow.com/a/11324894/12924700 过滤掉所有用单引号/双引号括起来的字符。
虽然上面的代码满足了上面的 3 个用例。 但是当用户输入
const testStr = '"user input invalid string \' :shouldIgnoreThisNamedParam \' in a string"'
extractNamedParam(testStr) // should return [] but it returns [":shouldIgnoreThisNamedParam"] instead
我确实访问了 hibernate 的源代码以查看命名参数是如何在那里提取的,但我找不到正在工作的算法。请帮忙。
【问题讨论】:
标签: javascript regex hibernate named-parameters string-algorithm