final Pattern pattern = Pattern.compile("^([a-zA-Z]+)? (\\w+)$"); final Matcher matcher = pattern.matcher("ABC _012_"); if (matcher.matches()) { final String group1 = matcher.group(1); final String group2 = matcher.group(2); System.out.println(group1); System.out.println(group2); }