搜索字符串中的特定部分

时间:2014-08-11 19:02:31

标签: java android

所以我正在制作这个txt文档,字符串也会写出大约100-2000行的不同信息。从这里我希望能够复制特定的部分,如名称,并将它们写成一个新的文件,所以我想知道是否有人可以帮助做一个例子

我只想将字符串的名称,地址和电话拉出作为示例,并将其写入文件:

nameadress=johndoe&adress=newyork163thdowntown&phone=+341431242

基本上我想要 找到nameadress,地址,手机复制=和&之间的所有内容

依此类推,如果中间有垃圾数据我想要忽略:)所以我只得到这些:)

2 个答案:

答案 0 :(得分:0)

您可以使用str.split()

执行此操作
String str = "nameadress=johndoe&adress=newyork163thdowntown&phone=+341431242";
String[] firstSplit = str.split("&");

System.out.println(firstSplit[0]); // Prints nameadress=johndoe
System.out.println(firstSplit[1]); // Prints adress=newyork163thdowntown
System.out.println(firstSplit[2]); // Prints phone=+341431242

String name = firstSplit[0].split("=")[1]; // johndoe
String address = firstSplit[1].split("=")[1]; // newyork163thdowntown
String phone = firstSplit[2].split("=")[1]; // +341431242

然后你可以将这三个字符串写入文件

为了忽略任何其他数据,您可以执行以下操作:

String str = "nameadress=johndoe&age=15&sex=female&adress=newyork163thdowntown&phone=+341431242";
String name = str.split("nameadress=")[1].split("&")[0];
String adress = str.split("adress=")[1].split("&")[0];
String phone = str.split("phone=")[1]; // This is the end of the String so we do not need to split("&")

答案 1 :(得分:0)

这听起来像是你想要解析器的东西。有关使用Guava库的一个很好的示例,请参阅此答案。 Guava: Splitter and considering Escaping?

您可以使用它来分隔字符串'&'字符(并考虑您使用的任何转义字符)。一旦你将它们分成:

nameadress=johndoe

adress=newyork163thdowntown

phone=+341431242

使用Guava Splitter类进一步分割每个字符串相当简单。

或者,你可以改为序列化为JSON,它有库。

相关问题