gpt4 book ai didi

java - 如何使用正则表达式从格式字符串中获取字符串元素?

转载 作者:行者123 更新时间:2023-12-02 10:53:14 25 4
gpt4 key购买 nike

我的输入字符串是这样的:

 String msgs="<InfoStart>\r\n" 
+ "id:1234\r\n"
+ "phone:912119882\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n"
+"<InfoStart>\r\n"
+ "id:5678\r\n"
+ "phone:912119881\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n";

现在我可以使用正则表达式来获取信息数组: private static Pattern patter= Pattern.compile("InfoStart>([\\s\\S]*?)<InfoEnd>"); ,但是如何使用正则表达式获取id,电话?我尝试编写代码,但失败了,如何修复它?

 private static Pattern infP = Pattern.compile("<InfoStart>([\\s\\S]*?)<InfoEnd>");   
private static Pattern lineP = Pattern.compile(".*?\r\n");
final java.util.regex.Matcher matcher = patter.matcher(msgs);
while (matcher.find()){
String item = matcher.group(1);
Matcher matcherLine = lineP.matcher(item);
while(matcherLine.find()){
if(matcherLine.groupCount()>0){
String value= matcherLine.group(1);
int firstIndex=value.indexOf(":");
System.out.println("key:"+value.substring(0, firstIndex)+"value:"+value.substring(firstIndex+1));
}
}
}

最佳答案

也许你可以试试这个:

    Pattern xmlPattern = Pattern.compile("<InfoStart>\\s+id:(\\d+)\\s+phone:(\\d+)\\s+info_type:(\\d+)\\s+<InfoEnd>");
Matcher matcher = xmlPattern.matcher(msgs);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
}

输出:

1234
912119882
1
5678
912119881
1

但我还是要像 Tim Biegeleisen 提到的那样,你最好使用其他方法来解析 XML 字符串。

另外,你输入的字符串不正确,应该是:

    String msgs="<InfoStart>\r\n"
+ "id:1234\r\n"
+ "phone:912119882\r\n"
+ "info_type:1\r\n"
+ "<InfoEnd>\r\n" // you lack an open double quote;
+"<InfoStart>\r\n"
+ "id:5678\r\n"
+ "phone:912119881\r\n"
+ "info_type:1\r\n"
+ "<InfoEnd>\r\n"; // you lack an open double quote;

关于java - 如何使用正则表达式从格式字符串中获取字符串元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com