The simple way is to split the source string first and then to run 2 separate regular expressions against 2 parts.
Pattern pCodeName = Pattern.compile("codeName=(.*)");
Pattern pCodeValue = Pattern.compile("codeValue=(.*)");
String[] parts = str.split("\\&");
Matcher m = pCodeName.matcher(parts[0]);
String codeName = m.find() ? m.group(1) : null;
String codeValue = null;
if (parts.length > 1) {
m = pCodeValue.matcher(parts[1]);
codeValue = m.find() ? m.group(1) : null;
}
}
But if you want you can also say:
Pattern p = Pattern.compile("codeName=(\\w+)(\\&codeValue=(\\w+))?");
Matcher m = p.matcher(str);
String codeName = null;
String codeValue = null;
if (m.find()) {
codeName = m.group(1);
codeValue = m.groupCount() > 1 ? m.group(2) : null;
}