我对正则表达式缺乏经验,对 JAVA 也很生疏,所以这里的一些帮助将不胜感激。
所以我有一个以下形式的字符串:
statement|digit|statement
statement|digit|statement
等等
where 语句可以是字符、数字和空格的任意组合。 我想解析这个字符串,以便将每行的第一个和最后一个语句保存在单独的字符串数组中。
例如,如果我有一个字符串:
cats|1|short hair and long hair
cats|2|black, blue
dogs|1|cats are better than dogs
我希望能够将字符串解析为两个数组。
Array one = [cats], [cats], [dogs]
Array two = [short hair and long hair],[black, blue],[cats are better than dogs]
Matcher m = Pattern.compile("(\\.+)|\\d+|=(\\.+)").matcher(str);
while(m.find()) {
String key = m.group(1);
String value = m.group(2);
System.out.printf("key=%s, value=%s\n", key, value);
}
如果我的输出正确,我会继续将键和值添加到单独的数组中,但运气不佳。任何有关此问题的帮助将不胜感激。
最佳答案
这是一个使用正则表达式的解决方案:
public class ParseString {
public static void main(String[] args) {
String data = "cats|1|short hair and long hair\n"+
"cats|2|black, blue\n"+
"dogs|1|cats are better than dogs";
List<String> result1 = new ArrayList<>();
List<String> result2 = new ArrayList<>();
Pattern pattern = Pattern.compile("(.+)\\|\\d+\\|(.+)");
Matcher m = pattern.matcher(data);
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
result1.add(key);
result2.add(value);
System.out.printf("key=%s, value=%s\n", key, value);
}
}
}
这是一个很棒的网站,可以帮助您使用正则表达式 http://txt2re.com/表达式。在第一步中输入一些示例文本。选择第 2 部分中您感兴趣的部分。并在第 3 步中选择一种语言。然后复制、粘贴和按摩它吐出的代码。
关于java - 如何使用正则表达式正确分割/解析该字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31840211/