簡體   English   中英

提取Javascript中的JPA命名參數

[英]Extract JPA Named Parameters in Javascript

我正在嘗試在 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 的源代碼,看看那里是如何提取命名參數的,但我找不到正在做這項工作的算法。 請幫忙。

您可以使用

/"[^\\"]*(?:\\[\w\W][^\\"]*)*"|'[^\\']*(?:\\[\w\W][^\\']*)*'|(:\w+)/g

僅獲取第 1 組值。 請參閱正則表達式演示 正則表達式匹配單引號/雙引號之間的字符串並捕獲: + 所有其他上下文中的一個或多個單詞字符。

請參閱 JavaScript 演示:

 const re = /"[^\\"]*(?:\\[\w\W][^\\"]*)*"|'[^\\']*(?:\\[\w\W][^\\']*)*'|(:\w+)/g; const text = "to_timestamp_tz(:FROM_DATE, 'YYYY-MM-DD\"T\"HH24:MI:SS')"; let matches=[], m; while (m=re.exec(text)) { if (m[1]) { matches.push(m[1]); } } console.log(matches);

詳情

  • "[^\\"]*(?:\\[\w\W][^\\"]*)*" - 一個" ,然后是"\ ( [^"\\]*以外的零個或多個字符[^"\\]* ),然后是任何轉義字符( \\[\w\W] )的零次或多次重復,后跟除"\之外的零次或更多字符,然后是"
  • | - 或者
  • '[^\\']*(?:\\[\w\W][^\\']*)*' - 一個' ,然后是'\ ( [^'\\]*以外的零個或多個字符[^'\\]* ),然后是任何轉義字符 ( \\[\w\W] ) 的零次或多次重復,后跟除'\之外的零次或多次字符,然后是'
  • | - 或者
  • (:\w+) - 第 1 組(這是我們需要獲取的值,rest 僅用於處理必須忽略匹配的一些文本):一個冒號和一個或多個單詞字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM