1

I have the line read from a file as follows:

ABC: Def, XYZ-ID: Xbase::Something, here, 90, EFG: something: again

The key words are ABC, XYZ-ID and EFG and the values of these key words follow.

How do I process the line such that I can further use the code below to process the key and value accordingly:

String[] keyValArray = str.split(":");
String key = keyValArray[0];
String val = keyValArray[1];

P.S: The key words are all in capitals.

Thanks in advance.

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
Vidya
  • 233
  • 3
  • 11
  • Are the keywords allways the same? – mambax Jul 27 '15 at 05:54
  • @m4mbax - all key words are not the same. – Vidya Jul 27 '15 at 05:55
  • So you looking for a parser searching for this pattern: "P1:P2" where P1 and P2 can be anything and you want to have separate strings for P1 and P2? – mambax Jul 27 '15 at 05:56
  • 2
    as per the rules of SO (and for your own good). you should try some by yourself, and if you get stuck, show us what you have, and tell us what goes wrong with it. this is a very good task to learn some programming! see `String` and maybe `StringBuilder` documentation in the JavaDoc. – hoijui Jul 27 '15 at 05:57

1 Answers1

2

If you are okay using regular expressions and are expecting three variables, you could use something like this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
String str = "....";
Pattern varPattern = Pattern.compile("^.*?:(.*),.*?:(.*),.*?:(.*)$");
Matcher varMatcher = varPattern.matcher(str);
while(varMatcher.find()) {
    //do something with varMatcher.group(1)
}
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
  • Just out of curiousity and maybe for the help for OP, how do you use this regex to extract stuff? :S I only know regex as kind of validation... – mambax Jul 27 '15 at 06:02
  • 2
    @m4mbax: regex also typically has "capture groups" that can be used to extract bits of the match. Check it out, it's really handy, as long as you don't try to use it to [parse html](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – Ron Thompson Jul 27 '15 at 06:18