What I have wrong? When I set variable param=”MOON” I need get 333#444 but I’m getting: 333#444:JUPITER=555. So I just need one value at a time.
final String parameters = "WORLD=111#222:MOON=333#444:JUPITER=555:SATURN=666:";
final String param = "MOON";
Pattern pattern = Pattern.compile("(.*)(" + param + ")=(.*)(:+)(.*)");
Matcher matcher = pattern.matcher(parameters);
if(matcher.matches()) {
System.out.println("3: " + matcher.group(3)); // Value that I needed: 333#444
}
Thank you.
I’m not totally sure, but maybe what you want is extract all key=value fields? If that is the case you should split your string at the
:character and process all parts by themselves. Then match those string parts with the regular expression([^=]+)=(.*)or, better, simply split each part at the=character. In this case you won’t even need regular expressions and possibly save program execution time! It’s easy to find theMOON= ...expression by search forMOON.EDIT: I did the following old Java style test program (most probably can be improved):
Output:
In many cases using a regular expression is overkill, it can often be avoided and you save execution time. If you have a very long string you might just search for
MOONand from there for the next:or end-of-string and then use split, but I would maybe use a regular expression in this case. It all depends if you need the other fields as well or not.