0

我不太擅长正则表达式,需要一些帮助。

我有一个类似于以下的字符串:

[{type='(type here)', field='(field here)', value='(value here)'},{...},...,{...}]

我正在尝试将其与以下正则表达式匹配:

^\[(\{type=\'(.*)\', field=\'(.*)\', value=\'(.*)\'\},*)*\]$

但它不匹配。然后我调试了。这是我用于调试的正则表达式:

\[(\{(.*)\}\]

这是字符串:

[{type='cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost', field='29 versions', value='250'}]

这是比赛:

{type='cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost', field='29 versions', value='250'}

我明白为什么这个字符串是匹配的。我不明白为什么没有匹配其他字符串。我希望其他匹配的字符串是:

  1. {type='cost', field='flag & e band 100s ($1/M's)', value='680'},

  2. {type='cost', field='29 个版本', value='250'}

为什么没有进行这些比赛?

4

4 回答 4

0

这有帮助吗:

^ matches at the start of the string
\[ matches "["
(
    \{type=\' matches "{type='"
    (
        .* matches "cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost"
    ) captures "cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost"
    \', field=\' matches ', field='
    (
        .* matches "29 versions"
    ) captures "29 versions"
    \', value=\' matches "', value='"
    (
        .* matches "250"
    ) captures "250"
    \'\} matches "'}"
    ,* matches ""
)* captures "{type='cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost', field='29 versions', value='250'}" (first and only repeat)
\] matches "]"
$ matches at the end of the string

因此,第 1 组捕获“[”和“]”之间的所有内容。

于 2011-07-29T16:35:50.947 回答
0

这可能是您使用了一个贪婪的量词而不是一个懒惰的量词。?在每个 's 之后插入一个*,看看是否可以解决任何问题。

于 2011-07-29T16:36:05.827 回答
0

问题是.*在子组内使用。贪婪地type=\'(.*)\'匹配,即它会产生cost', field='flag & e band 100s ($1/M's)', value='680'}, {type='cost.

另外:数据中的分隔符也存在于内容中,例如,您的模式试图解析field=\'(.*)\'但很难命中field='flag & e band 100s ($1/M's)',(注意'M.

所以我建议(如果你也想收集字段的内容):

  1. 注意“字段”的可能内容,以屏蔽子分组(如果数据来自外部源,请转义或找到更好的分隔符)。
  2. 避免像 Steve Wang 在他的回答中提到的那样贪婪,只按预期收集子组。

否则,仅在花括号分组上触发,即\{[^\}]+\}

于 2011-07-29T16:40:02.587 回答
0

这应该这样做:

    var str = "[{type='cost', field='flag & e band 100s ($1/M's)', value='680'},{type='cost', field='29 versions', value='250'}] ";
    var regexp = /\{[^\}]+\}/g;
    var m;
    while (m = regexp.exec(str)) {
        alert(m[0]);
    }

表达式绝对不必太复杂 -/\{[^\}]+\}/g意味着:

全局,(关闭正斜杠后的 g),给我所有以 { 开头,有一个或多个非 } 字符,并以 } 结尾的东西。

于 2011-07-29T16:56:22.313 回答