Michael Michael - 5 months ago 9
Java Question

Regex pattern not working properly on matcher

I have a string like this:

ben[0]='zc5u5';
icb[0]='M';
bild[0]='b1_413134.jpg';
ort[0]='Köln';kmm[0]=0.00074758603074103;alt[0]='18';
jti[0]=413134;
upd[0]='u41313486729.js';
jon[0]=0;
jco[0]=0;
jch[0]=0;
ben[1]='Oukg5';
icb[1]='M';
bild[1]='mannse.jpg';
jti[1]=412425;
upd[1]='u41242570092.js';
jon[1]=0;
jco[1]=0;
jch[1]=0;
ben[2]='Tester356';
icb[2]='M';
bild[2]='b1_247967.jpg';


I want to get the names from
ben[]
, for example the first one would be
zc5u5
.

I do currently have this code:

Pattern pattern = Pattern.compile("(ben\\[\\d+\\]=').+?'");
Matcher matcher = pattern.matcher(string);

LinkedList<String> list = new LinkedList<String>();

// Loop through and find all matches and store them into the List
while(matcher.find()) {
list.add(matcher.group());
}


Unfortunately the pattern does match the whole line, instead of just the value, e.g.
zc5u5
. What am I doing wrong?

Answer

You need two groups if you want to capture the index and the value, and I would add support for optional white-space around the assignment (\\s*). Something like,

Pattern pattern = Pattern.compile("ben\\[(\\d+)\\]\\s*=\\s*'(.+)';");
Matcher matcher = pattern.matcher(string);
if (matcher.matches()) {
    System.out.printf("index %s = %s%n", matcher.group(1), matcher.group(2));
}
Comments