如何使用索引值拆分我的正则表达式

时间:2019-04-24 10:10:42

标签: java arrays string split

我需要拆分正则表达式,例如“嘿,我,名字,“约翰,男孩”,年龄,男性”。 当我尝试使用(,)进行拆分时,将其拆分为嘿,我,姓名,约翰,男孩,年龄,男性。 但我需要输出为


我的
名称
约翰,男孩
年龄
男性

 line="hey,my,name,"john,boy",age,male";
    String[] line1 = line.split(",")
           String slNo = line1[0];
           String customerId = line1[1];
           String customerCategory = line1[2];

输出:嘿,我,名字,约翰,男孩,年龄,男性

1 个答案:

答案 0 :(得分:3)

使用find(使用此正则表达式)从group1获取所需的字符串比使用split更容易,并且如果group1为null,则仅进行整个匹配,

"([^"]+)"|[^,]+

Regex Demo

检查此Java代码,

String s = "hey,my,name,\"john,boy\",age,male";
Pattern p = Pattern.compile("\"([^\"]+)\"|[^,]+");
Matcher m = p.matcher(s);
List<String> words = new ArrayList<>();

while (m.find()) {
    words.add(m.group(1) == null ? m.group() : m.group(1)); // store all the found words in this ArrayList
}

String[] line1 = words.toArray(new String[words.size()]);
String slNo = line1[0];
String customerId = line1[1];
String customerCategory = line1[2];

words.forEach(System.out::println);

根据需要打印字符串,

hey
my
name
john,boy
age
male