代码之家  ›  专栏  ›  技术社区  ›  Genhain

在忽略错误空格的情况下,在小括号内为值指定正则表达式

  •  0
  • Genhain  · 技术社区  · 6 年前

    Hello {{{ name }}}, {{{greeting}}}. what is your favourite code related website {{ code question website!!! ?? ? }}? here is some random fact {{ random fun fact }}

    • 第1组:“{”和前导空格
    • 第二组:我们想要的价值
    • 第3组:尾随空格和“}”

    到目前为止,我已经得出以下结论 ({{2,3}\s*)([^{}]*)(\s*}{2,3}) 但是如果你检查了第二组匹配的捕获组,那么我们想要的值…这是好的,但是后面的空白应该在第三组中。即

    Ruby实现 str.gsub(/({{2,3}\s*)([^{}]*)(\s*}{2,3})/) { |_| $~[1]+Base64.urlsafe_encode64($~[2].strip, padding: false)+$~[3] }

    1 回复  |  直到 6 年前
        1
  •  2
  •   Tim Biegeleisen    6 年前

    一个选择是 scan 数组中的输入字符串使用以下模式匹配:

    \{+\s*([^{}]+)\s*\}+
    

    这将捕获(大概)嵌套的大括号集之间出现的所有内容。然后,我们可以将该数组从单个捕获组展平为字符串匹配的单个级别数组,然后进行收集,删除前导和尾随空格。

    str = "Hello {{{ name }}}, {{{greeting}}}. what is your favourite code related website {{ code question website!!! ?? ? }}? here is some random fact {{ random fun  fact    }}"
    arr = str.scan(/\{+\s*([^{}]+)\s*\}+/)
    print arr.flatten.collect{|x| x.strip || x }
    
    ["name", "greeting", "code question website!!! ?? ?", "random fun  fact"]
    
        2
  •  0
  •   Cary Swoveland    5 年前
    str = "Hello {{{ name }}}, {{{greeting}}}. what is your favourite code related website {{ code question website!!! ?? ? }}? here is some random fact {{ random fun  fact    }}"
    

    r = /
        {+[ ]*     # match 1+ left braces then 0+ spaces
        \K         # forget everything matched so far
        .+?        # match 1+ characters, lazily
        (?=[ ]*})  # match 0+ spaces then 1 right brace in a positive lookahead
        /x
    
    str.scan(r)
      #=> ["name", "greeting", "code question website!!! ?? ?", "random fun  fact"]
    

    此正则表达式按常规编写:

    /{+ *\K.+?(?= *})/
    

    在自由间距模式下,在解析表达式之前,空格会被剥离,因此作为表达式一部分的空格必须受到保护。我把它们放在一个角色类中。或者,可以转义空间。根据需要,可以将空格与 \s , [[:space:]] \p{Space} [[:blank:]] \p{Blank} .