简体   繁体   中英

How to split this string using Java Regular Expressions

I want to split the string

String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";

to

name
employeeno
dob
joindate

I wrote the following java code for this but it is printing only name other matches are not printing.

String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";

Pattern pattern = Pattern.compile("\\[.+\\]+?,?\\s*" );

String[] split = pattern.split(fields);
for (String string : split) {
    System.out.println(string);
}

What am I doing wrong here?

Thank you

This part:

\\[.+\\]

matches the first [ , the .+ then gobbles up the entire string (if no line breaks are in the string) and then the \\\\] will match the last ] .

You need to make the .+ reluctant by placing a ? after it:

Pattern pattern = Pattern.compile("\\[.+?\\]+?,?\\s*");

And shouldn't \\\\]+? just be \\\\] ?

The error is that you are matching greedily . You can change it to a non-greedy match:

Pattern.compile("\\[.+?\\],?\\s*")
                      ^

http://gskinner.com/RegExr/?2sa45上有一个在线正则表达式测试器,当您尝试了解正则表达式以及如何将其应用于给定输入时,它将为您提供很多帮助。

WOuld it be better to use Negated Character Classes to match the square brackets? \\[(\\w+\\s)+\\w+[^\\]]\\]

You could also see a good example how does using a negated character class work internally (without backtracking)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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