2008-12-11 125 views
2

什麼是從字符串中提取這樣的鍵和值的最佳方式:最簡單的方法來將字符串分割成鍵/值

var myString = 'A1234=B1234'; 

我本來是這樣的:

myString.split('='); 

而且但可以使用等號(=)作爲字符串中的鍵或值,並且字符串可以有引號,如下所示:

var myString = '"A123=1=2=3=4"="B1234"'; 

字符串也只能有一對引號和空格:

var myString = ' "A123=1=2=3=4" = B1234 '; 

我不是在正則表達式很好,但我猜這是前進的道路?

我想與落得是兩個變量,鍵和值,在上面的情況下,密鑰變量將最終被A123 = 1 = 2 = 3 = 4和變量的值將是B1234

如果沒有現值,例如,如果是這樣的原始字符串:

var myString = 'A1234'; 

然後我希望的關鍵變量是「A1234」和變量的值,爲空或假 - 或者我可以測試的東西。

任何幫助表示讚賞。

+0

您確定要允許=作爲鍵或值中的有效字符嗎? – 2008-12-11 01:27:32

+0

與之關係鬆散:http://stackoverflow.com/questions/328387/regex-to-replace-all-n-in-a-string-but-no-those-inside-code-code-tag – strager 2008-12-11 01:45:35

回答

2

什麼,我傾向於在配置文件中做的是確保有沒有可能性分隔符可以進入鍵或值。

有時候,如果你可以說「不允許」字符,那麼這很容易,但是我不得不在某些地方對這些字符進行編碼。

我通常把它們加起來,這樣如果你想要一個'='字符,你必須放入%3d(%'字符爲%25,所以你不認爲它是一個十六進制字符)。你也可以對任何字符使用%xx,但這兩個只需要需要

通過這種方式,您可以檢查該行以確保其只有一個「=」字符,然後對該鍵和值進行後處理,將十六進制字符轉換爲真正的字符。

4

不能用一行代碼的幫助,但我會建議用簡單的方式:

var inQuote = false; 
for(i=0; i<str.length; i++) { 
    if (str.charAt(i) == '"') { 
     inQuote = !inQuote; 
    } 
    if (!inQuote && str.charAt(i)=='=') { 
     key = str.slice(0,i); 
     value = str.slice(i+1); 
     break; 
    } 
} 
+0

不要忘記用反斜線來轉義封閉的引號!但這與我所採用的方法大致相同。正則表達式在這裏不是正確的工具。這是解析器的工作。 – benjismith 2008-12-11 01:39:18

+0

感謝你們,我爲將來保存下來 - 對於這個特殊問題,我會忽略那些「平等」的標誌並思考它,用戶沒有真正需要有機會引用引號。 - 我將在用戶輸入時剝離它們。 – James 2008-12-11 01:49:48

3
/^(\"[^"]*\"|.*?)=(\"[^"]*\"|.*?)$/ 
2

如果我們的規則與等號所有按鍵需要嵌入引號內,那麼這個效果很好(我無法想象任何好的理由一鍵內又讓轉義引號)。

/^    # Beginning of line 
    \s*    # Any number of spaces 
    (" ([^"]+) " # A quote followed by any number of non-quotes, 
        # and a closing quote 
    | [^=]*   # OR any number of not equals signs 
    [^ =]   # and at least one character that is not a equal or a space 
)    
    \s*    # any number of spaces between the key and the operator 
    =    # the assignment operator 
    \s*    # Any number of spaces 
    (.*?\S)   # Then any number of any characters, stopping at the last non-space 
    \s*    # Before spaces and... 
    $    # The end of line. 

/

在Java中

現在,屬性文件(他們打破在第一「:」或「=」,雖然)你可以通過把「\」在該行的末尾有一個屬性多行,所以它會有點棘手。