最简单的方法来将字符串分割成键/值
什么是从字符串中提取这样的键和值的最佳方式:最简单的方法来将字符串分割成键/值
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”和变量的值,为空或假 - 或者我可以测试的东西。
任何帮助表示赞赏。
什么,我倾向于在配置文件中做的是确保有没有可能性分隔符可以进入键或值。
有时候,如果你可以说“不允许”字符,那么这很容易,但是我不得不在某些地方对这些字符进行编码。
我通常把它们加起来,这样如果你想要一个'='字符,你必须放入%3d(%'字符为%25,所以你不认为它是一个十六进制字符)。你也可以对任何字符使用%xx,但这两个只需要需要。
通过这种方式,您可以检查该行以确保其只有一个“=”字符,然后对该键和值进行后处理,将十六进制字符转换为真正的字符。
不能用一行代码的帮助,但我会建议用简单的方式:
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;
}
}
不要忘记用反斜线来转义封闭的引号!但这与我所采用的方法大致相同。正则表达式在这里不是正确的工具。这是解析器的工作。 – benjismith 2008-12-11 01:39:18
感谢你们,我为将来保存下来 - 对于这个特殊问题,我会忽略那些“平等”的标志并思考它,用户没有真正需要有机会引用引号。 - 我将在用户输入时剥离它们。 – James 2008-12-11 01:49:48
/^(\"[^"]*\"|.*?)=(\"[^"]*\"|.*?)$/
如果我们的规则与等号所有按键需要嵌入引号内,那么这个效果很好(我无法想象任何好的理由一键内又让转义引号)。
/^ # 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中现在,属性文件(他们打破在第一“:”或“=”,虽然)你可以通过把“\”在该行的末尾有一个属性多行,所以它会有点棘手。
您确定要允许=作为键或值中的有效字符吗? – 2008-12-11 01:27:32
与之关系松散: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