JavaScript正则表达式,用于拆分带符号分隔的字符串

JavaScript正则表达式,用于拆分带符号分隔的字符串,javascript,regex,Javascript,Regex,我已经干了好几个小时了,现在已经走到了死胡同。我在各地都读过正则表达式,但在匹配任何比基本模式更复杂的东西时仍然有困难 所以,我的问题是: 我需要将一个以字符串分隔的“&”拆分为一个对象列表,但我还需要考虑包含符号的值 如果你能提供任何帮助,请告诉我 var subjectA='myTestKey=这是我的测试数据&so&myOtherKey=这是另一个值' 更新: ( # Match and capture in group number 1: [^&=]+ # On

我已经干了好几个小时了,现在已经走到了死胡同。我在各地都读过正则表达式,但在匹配任何比基本模式更复杂的东西时仍然有困难

所以,我的问题是:

我需要将一个以字符串分隔的“&”拆分为一个对象列表,但我还需要考虑包含符号的值

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

var subjectA='myTestKey=这是我的测试数据&so&myOtherKey=这是另一个值'

更新:

(        # 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.
好的,首先,谢谢你的热情周到的回复。为了让大家了解我为什么要这么做,我要用JavaScript创建一个cookie实用程序,它更智能,支持ASP

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

[
    [myTestKey, this is my test data & such],
    [myOtherKey, this is the other value]]
]
它甚至在一些更极端的例子中起作用,允许我转动字符串,如:

var subjectB='thistuff==myv=value-me==&other-things=&thatsuff=my-other-value-too'

进入:

但是,当您使用以下字符串时:

var subjectC='me===regex对&me&you=&you=nah来说很难,其实你只是一个n00b'

一切又出了问题。我理解为什么这是由于上面的正则表达式导致的(这是一个非常棒的解释),但我(显然)对正则表达式不太熟悉,无法找到解决方法

就重要性而言,我需要这个cookie实用程序能够读写能够被ASP和ASP.NET理解的cookie,反之亦然。从上面的例子来看,我认为我们已经尽了最大的努力,但是如果我错了,任何额外的输入都将不胜感激

tl;dr-差不多了,但是否可以解释异常值,如
subjectC

var subjectC='me===regex对&me&you=&you=nah来说很难,其实你只是一个n00b'

实际输出:

[
    [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]
]
再次感谢你的帮助。另外,我实际上在使用RegExp时变得更好了。。。疯了

我需要将分隔为字符串的“
&
”拆分为一个对象列表,但我还需要考虑包含符号的值

你不能

任何允许字符同时显示为特殊字符和数据的数据格式都需要一条规则(通常是将字符表示为数据的不同方式)来区分这两种格式

  • HTML有
    &
    &
  • URI有
    &
    %26
  • CSV有
  • 大多数编程语言都有
    \”
您的字符串没有任何规则来确定
&
是分隔符还是符号,因此您无法编写能够区分两者的代码

我需要将分隔为字符串的“
&
”拆分为一个对象列表,但我还需要考虑包含符号的值

你不能

任何允许字符同时显示为特殊字符和数据的数据格式都需要一条规则(通常是将字符表示为数据的不同方式)来区分这两种格式

  • HTML有
    &
    &;
  • URI有
    &
    %26
  • CSV有
  • 大多数编程语言都有
    \”

您的字符串没有任何规则来确定
&
是分隔符还是符号,因此您无法编写能够区分两者的代码。

如果您的键不能包含符号,则可以:

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);
}
说明:

(        # 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.

这可能不是执行此操作的最有效方法(因为在每次匹配过程中需要多次检查前瞻性断言),但它非常简单。

如果您的键不能包含符号,则可以:

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);
}
"myTestKey=this is my test data & such&myOtherKey=this is the other value".split(/&?([a-z]+)=/gi)
说明:

(        # 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.
这可能不是执行此操作的最有效方法(因为在每次匹配过程中需要多次检查前瞻断言),但它相当简单

"myTestKey=this is my test data & such&myOtherKey=this is the other value".split(/&?([a-z]+)=/gi)
这将返回:

["", "myTestKey", "this is my test data & such", "myOtherKey", "this is the other value"]
但是,如果
这是我的测试数据,这样的
也会包含一个
=
符号,比如
这是我的测试数据,这样的=其他东西,你就不走运了

这将返回:

["", "myTestKey", "this is my test data & such", "myOtherKey", "this is the other value"]
但是,如果
这是我的测试数据,这样的
也会包含一个
=
符号,比如
这是我的测试数据,这样的=其他东西,那么你就不走运了。

我建议你使用

.split(/(?:=|&(?=[^&]*=))/);
检查

我建议您使用

.split(/(?:=|&(?=[^&]*=))/);

选中

True,建议使用区分规则;如果为True,则如果某个键包含“与”或等号,则RegExp模式可能会失败符号,但它可以用普通JavaScript完成。您只需从键值对的角度考虑,并接受一个事实,即可能没有一个RegExp模式来解决这个问题:您必须将字符串拆分为一个数组,循环遍历元素,并在必要时合并它们:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <style id="styleTag" type="text/css">
        </style>
        <script type="text/javascript">
        window.onload = function()
        {
            // test data
            var s = "myTestKey=this is my test data & such&myOtherKey=this is the other value&aThirdKey=Hello=Hi&How are you&FourthKey=that's it!";

            // the split is on the ampersand symbol!
            var a = s.split(/&/);

            // loop through &-separated values; we skip the 1st element
            // because we may need to address the previous (i-1) element
            // in our loop (you are REALLY out of luck if a[0] is not a
            // key=value pair!)
            for (var i = 1; i < a.length; i++)
            {
                // the abscence of the equal symbol indicates that this element is
                // part of the value of the previous key=value pair, so merge them
                if (a[i].search(/=/) == -1)
                    a.splice(i - 1, 2, a[i - 1] + '&' + a[i]);
            }

            Data.innerHTML = s;
            Result.innerHTML = a.join('<br/>');
        }
        </script>
    </head>
    <body>
        <h1>Hello, world.</h1>
        <p>Test string:</p>
        <p id=Data></p>
        <p>Split/Splice Result:</p>
        <p id=Result></p>
    </body>
</html>

window.onload=函数()
{
//测试数据
var s=“myTestKey=这是我的测试数据&soke&myOtherKey=这是另一个值&aThirdKey=Hello=Hi&How you&FourthKey=就是这样!”;
//分裂在符号符号上!
var a=s.分割(/&/);
//循环通过&分离v