简体   繁体   English

将字符串拆分为键和值对

[英]Splitting a string into key & value pair

I am spliting string with '&' . 我正在用'&'分割字符串。 For Example: 例如:

password=XXXXXXXXX&username=XXXXXXXXXXX

Now if suppose my password contains '&' then i am facing issue here that the password gets trimed on first occurence of '&'. 现在如果假设我的密码包含'&',那么我在这里遇到的问题是密码在第一次出现'&'时被激活。

Example: 例:

password=disney&123&username=XXXXXXXXXXX

So my output will be as follows: 所以我的输出如下:

password=disney 
123 
username=XXXXXXXXXXX

But I want my output as: 但我希望我的输出为:

password=disney&123 
username=XXXXXXXXXXX

Please guide me as i am new to java. 请指导我,因为我是java的新手。 And i want to split the string using '&' only and my password may conatin '&' it depends on users. 我想只使用'&'分割字符串,我的密码可能conatin'&'它取决于用户。

Thanks in Advance, Ritesh 在此先感谢Ritesh

A more simple solution would be to use the URL encoding completly. 一个更简单的解决方案是完全使用URL编码。 Here you are using only the separator system but you should also use the encoding. 这里只使用分隔符系统,但您也应该使用编码。

So when you build the String, encode the values, this will replace some character, you can use the complet solution or simply replace the & with the value of your choice (but I would not do that). 因此,当您构建String时,对值进行编码,这将替换某些字符,您可以使用complet解决方案或只是将&替换为您选择的值(但我不会这样做)。

Then, when you have split the String contains only the & used to separate values, decode the values (to recreate the original values). 然后,当您拆分时,String只包含&用于分隔值,解码值(重新创建原始值)。

This would be exactly the same as sending a request to a WebService, since you use the same pattern, this would seems more logic. 这与向WebService发送请求完全相同,因为您使用相同的模式,这似乎更逻辑。

  • Encode the values 编码值
  • Concat the values with & 使用& Concat值
  • Send the String 发送字符串
  • Split the String using & 使用&拆分字符串
  • Decode the values 解码值
String[] strs="password=disney&123&username=XXXXXXXXXXX".split("&username=");
strs[1]="username="+strs[1];
System.out.println(strs[0]);
System.out.println(strs[1]);

-- -

Edit: 编辑:

//This is a slightly more generalized method
String[] strs="username=XXXXXXXXXXX&password=disney&123".split("&(?=(username|password)=)");
System.out.println(strs[0]);
System.out.println(strs[1]);

-- -

Edit: 编辑:

//more generalized method
String[] strs="username=XXXXXXXXXXX&password=disney&123".split("&(?=([a-zA-Z0-9]+)=)");
for(String str : strs)
    System.out.println(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM