簡體   English   中英

JavaScript正則表達式拆分與符號分隔的字符串

[英]JavaScript Regular Expression to Split an Ampersand Delimited String

我已經在這里呆了幾個小時了,我快要死了。 我到處都讀過正則表達式,但是在比基本模式更復雜的事物上匹配時仍然遇到困難。

所以,我的問題是這樣的:

我需要將以字符串分隔的“&”分割為對象列表,但是我也需要考慮包含“與”號的值。

如果您可以提供任何幫助,請告訴我。

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

更新:

首先,感謝您的出色,周到的答復。 為了讓我有一個背景,我打算在JavaScript中創建一個cookie實用程序,該實用程序更加智能並且支持ala ASP。

話雖如此,我發現下面的RegExp /([^&=\\s]+)=(([^&]*)(&[^&=\\s]*)*)(&|$)/g了我需要的99%。 我更改了以下貢獻者建議的RegExp,也忽略了空格。 這使我可以將上面的字符串轉換為以下集合:

[
    [myTestKey, this is my test data & such],
    [myOtherKey, this is the other value]]
]

它甚至可以在一些更極端的示例中使用,使我可以像這樣輸入字符串:

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

進入:

[
    [thisstuff, ==myv=alue me==& other things=],
    [thatstuff, my other value too]
]

但是,當您使用類似以下的字符串時:

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

一切再次擺脫困境。 我理解為什么上述正則表達式會導致這種情況的發生(對一個非常棒的解釋表示敬意),但是我(顯然)對正則表達式不滿意,無法解決。

就重要性而言,我需要此cookie實用程序能夠讀取和寫入ASP和ASP.NET可以理解的cookie,反之亦然。 通過處理上面的示例,我認為我們已經盡力了,但是如果我錯了,任何其他輸入將不勝感激。

tl; subjectC差不多在那里,但是有可能考慮到諸如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]
]

與預期輸出:

[
    [me, ==regexs are hard for &me&you=],
    [you, nah, not really you\'re just a n00b]
]

再次感謝您的所有幫助。 另外,我實際上對RegExp感到越來越好……瘋狂。

如果您的密鑰不能包含&符,則可能是:

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.

這可能不是執行此操作的最有效方法(因為在每次比賽中都需要多次檢查前瞻性斷言),但它非常簡單。

我需要將以字符串分隔的“ & ”分割為對象列表,但是我也需要考慮包含&符號的值。

你不能

任何允許字符既作為特殊字符又作為數據出現的數據格式都需要一個規則(通常是將字符表示為數據的另一種方式),以使兩者有所區別。

  • HTML具有&&
  • URI具有&%26
  • CSV包含"""
  • 大多數編程語言都帶有"\\"

您的字符串沒有任何規則來確定&是定界符還是&符,因此您無法編寫能夠說明差異的代碼。

的確,建議使用區分規則,並且,如果鍵包含“&”號(或等號!)符號,則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>

輸出:

你好,世界。

測試字符串:

myTestKey =這是我的測試數據&such&myOtherKey =這是另一個值&aThirdKey = Hello =嗨&你好嗎&FourthKey =就是這樣!

拆分/拼接結果:

myTestKey =這是我的測試數據等
myOtherKey =這是另一個值
aThirdKey = Hello =嗨,你好嗎
FourthKey =就是這樣!

"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"]

但是,如果this is my test data & such還會包含=符號,就像this is my test data &such= something else ,那么您就不走運了。

我建議你用

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

檢查這個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM