棘手的正则表达式解析键值对

dth*_*ree 3 javascript regex

我花了一个多小时搞乱正则表达式模式,以便让find-and-replace一个复杂的字符串正常工作.

我需要像这样转换一个字符串:

foo a='b' c="d and e" wombat=true a fizz='buzz' "hello='goodbye'"
Run Code Online (Sandbox Code Playgroud)

并将其标准化为:

foo "a='b'" "c='d and e'" "wombat='true'" a "fizz='buzz'" "hello='goodbye'"
Run Code Online (Sandbox Code Playgroud)

在本质上:

  • key/value对都应该用双引号括起来,值用单引号括起来,不管它们之前是如何包装的.

  • 多间隔值必须先包装在单引号或双引号中,以便"包含"为值.


到目前为止,我正按照以下顺序玩正则表达式:

str = str.replace(/([a-zA-Z0-9]*)=("(.*?)"|'(.*?)')/g, '"$1=\'$2\'');
Run Code Online (Sandbox Code Playgroud)

但是,这有很多问题.

这有什么单一替代解决方案吗?

Tom*_*lak 6

/(['"]?)(\w+)=(?:(['"])((?:(?!\3).)*)\3|(\S+))\1/g
Run Code Online (Sandbox Code Playgroud)

"$2='$4$5'"
Run Code Online (Sandbox Code Playgroud)

给了通缉

foo "a='b'" "c='d and e'" "wombat='true'" a "fizz='buzz'" "hello='goodbye'"
Run Code Online (Sandbox Code Playgroud)

表达式如下:

(['"]?)            # group 1: either single or double quote, optional
(\w+)              # group 2: word characters (i.e. the "key")
=                  # a literal "="
(?:                # non-capturing group
  (['"])           #   group 3: either single or double quote
  (                #   group 4 (quoted value): 
    (?:(?!\3).)*   #     any character that's not the same as group 3
  )                #   end group 4
  \3               #   the quote from group 3  
  |                #   or...
  (\S+)            #   group 5 (non-quoted value, no spaces)
)                  # end non-capturing group
\1                 # whatever group 1 had, for good measure
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.:)我也添加了表达式的细分. (3认同)