【问题标题】:Regex - find all string function arguments in file正则表达式 - 在文件中查找所有字符串函数参数
【发布时间】:2020-09-23 20:19:49
【问题描述】:

我需要一个正则表达式,它将提取给定文本文件中的所有字符串函数参数。它是一个 PL/SQL 脚本文件,因此 '' 在字符串中转义了 '

一个例子:

foo('My foo arg! Something.') --> 'My foo arg! Something.'
bar('My bar arg', number) --> 'My bar arg'

// note the spaces
foo(   'My foo arg') --> 'My foo argument'
bar(   'My bar arg', number) --> 'My bar arg'

foo(''My escaped string'') --> ''My escaped string''
bar(''My escaped string'', number) --> ''My escaped string''

我写了一个简单的模式,但它没有按预期工作:

Pattern p = Pattern.compile("[\\s]*\\([\\s]*((([']{1,2})?))(([\\w\\W&&[^']&&]*)*((([']{2})?))*)*'",
                Pattern.UNICODE_CASE);
        Matcher m = p.matcher(text);

编辑

有效的例子是:

-- expected: 'My foo arg! Something.'
BEGIN
    foo('My foo arg! Something.');
END; 

-- expected: ''My foo arg! Something.'' or 'My foo arg! Something.'
DECLARE
 v_sql VARCHAR(4000) := 'SELECT foo(''My foo arg! Something.'') FROM sys.dual';
BEGIN
 EXECUTE IMMEDIATE v_sql;
END;

【问题讨论】:

  • 你确定你可以拥有foo(''My escaped string'')吗?不是foo('''My escaped string''')
  • 是的,我确定...
  • 但你说'' 表示'' 引用的子字符串中。 foo(''My escaped string'') 不是语法错误的例子吗?
  • 也许要说清楚,方法 foo 是字符串的一部分:'SELECT foo(''My escaped string'') FROM sys.DUAL'.
  • 但是'SELECT foo('My foo arg! Something.') FROM sys.dual' 会无效吗?你怎么描述的,这两个例子都不对。

标签: java regex plsql


【解决方案1】:

似乎我遗漏了一些东西,但这似乎有效:

'{1,2}[^']+'{1,2}

英文是这样写的:

  • '{1,2} - 查找 1 或 2 个单引号
  • [^']+ - 找到 1 个或多个不是单引号的字符
  • '{1,2} - 查找 1 或 2 个单引号

regex101上查看它的实际应用

【讨论】:

    【解决方案2】:

    听起来像是“查找所有带引号的字符串并尊重转义引号”的经典问题。这里的规范答案是:

    '(?:''|[^'])*'
    

    它匹配开引号,然后匹配任意数量的转义(双引号)或非引号,以右引号终止。

    https://regexr.com/564c3的演示

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多