用于分割符号分隔字符串的JavaScript正则表达式

elu*_*id8 1 javascript regex

我已经在这里待了好几个小时,而且我已经走到了尽头.我已经阅读了所有地方的正则表达式,但是我仍然无法匹配比基本模式更复杂的东西.

所以,我的问题是:

我需要将"&"分隔为字符串分割为对象列表,但我需要考虑包含&符号的值.

如果您能提供任何帮助,请告诉我.

var subjectA = 'myTestKey=this is my test data & such&myOtherKey=this is the other value';

更新:

好的,首先,谢谢你的精彩,深思熟虑的回应.为了说明我为什么要这样做的一些背景知识,那就是在JavaScript中创建一个更加智能的cookie实用程序并支持ASP的键.

话虽如此,我发现以下RegExp可以满足/([^&=\s]+)=(([^&]*)(&[^&=\s]*)*)(&|$)/g我所需要的99%.我更改了下面的贡献者建议的RegExp也忽略了空格.这允许我将上面的字符串转换为以下集合:

[
    [myTestKey, this is my test data & such],
    [myOtherKey, this is the other value]]
]
Run Code Online (Sandbox Code Playgroud)

它甚至适用于一些更极端的例子,允许我转换一个字符串,如:

var subjectB = 'thisstuff===myv=alue me==& other things=&thatstuff=my other value too';

成:

[
    [thisstuff, ==myv=alue me==& other things=],
    [thatstuff, my other value too]
]
Run Code Online (Sandbox Code Playgroud)

但是,当你拿一个像这样的字符串:

var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';

一切都变得糟透了.我理解为什么这是因为上面的正则表达式的结果(非常棒的解释的荣誉),但我(显然)对正则表达式来说不够舒服以找出解决方法.

至于重要性,我需要这个cookie实用程序能够读取和编写ASP和ASP.NET可以理解的cookie,反之亦然.从上面的例子开始,我认为我们已经尽可能地采取了它,但如果我错了,任何额外的输入将非常感激.

tl; dr - 几乎就在那里,但是可以解释像这样的异常值subjectC吗?

var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';

实际输出:

[
    [me, ==regexs are hard for &me],
    [you, ],
    [you, nah, not really you\'re just a n00b]
]
Run Code Online (Sandbox Code Playgroud)

与预期的输出:

[
    [me, ==regexs are hard for &me&you=],
    [you, nah, not really you\'re just a n00b]
]
Run Code Online (Sandbox Code Playgroud)

再次感谢您的帮助.另外,我实际上用RegExp变得更好...... Crazy.

Tim*_*ker 5

如果您的密钥不能包含&符号,则可能:

var myregexp = /([^&=]+)=(.*?)(?=&[^&=]+=|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
    key = match[1];
    value = match[2];
    // Do something with key and value
    match = myregexp.exec(subject);
}
Run Code Online (Sandbox Code Playgroud)

说明:

(        # Match and capture in group number 1:
 [^&=]+  # One or more characters except ampersands or equals signs
)        # End of group 1
=        # Match an equals sign
(        # Match and capture in group number 2:
 .*?     # Any number of characters (as few as possible)
)        # End of group 2
(?=      # Assert that the following can be matched here:
 &       # Either an ampersand,
 [^&=]+  # followed by a key (as above),
 =       # followed by an equals sign
|        # or
 $       # the end of the string.
)        # End of lookahead.
Run Code Online (Sandbox Code Playgroud)

这可能不是最有效的方法(因为在每次匹配期间需要多次检查的先行断言),但它相当简单.