There are a variety of ways you can accomplish this task
Regex
The pattern
"emp-id\\d+"
should achieve what you're wanting for both cases. The pattern matches "emp-id" plus 1 or more digits (\\d+).
public static void main(String[] args) throws Exception {
String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";
Matcher matcher = Pattern.compile("emp-id\\d+").matcher(case1);
// Changed from while to if cause we're only going to get the first match
if (matcher.find()) {
System.out.println(matcher.group());
}
matcher = Pattern.compile("emp-id\\d+").matcher(case2);
// Changed from while to if cause we're only going to get the first match
if (matcher.find()) {
System.out.println(matcher.group());
}
}
Results:
emp-id1545
emp-id8545
Java 8
Given that your data indicates that the character "/" is a delimiter. You can also use String.split() and Stream.filter() (Java 8) to find your String.
public static void main(String[] args) throws Exception {
String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";
System.out.println(Arrays.stream(case1.split("/")).filter(s -> s.startsWith("emp-id")).findFirst().get());
System.out.println(Arrays.stream(case2.split("/")).filter(s -> s.startsWith("emp-id")).findFirst().get());
}
Results:
emp-id1545
emp-id8545
Non Regex or Java 8
Still using "/" delimiter and "emp-id" you can use String.indexOf() and String.substring() to extract the String you're looking for.
public static void main(String[] args) throws Exception {
String case1 = "project/emp-id1545/ID-JHKDKHENNDHJSJ";
String case2 = "project/**dep**/emp-id8545/ID-GHFRDEEDE";
int index = case1.indexOf("emp-id");
System.out.println(case1.substring(index, case1.indexOf("/", index)));
index = case2.indexOf("emp-id");
System.out.println(case2.substring(index, case2.indexOf("/", index)));
}
Results:
emp-id1545
emp-id8545
CaseXalso part of your data? Does your data contain only one line or many lines?project/emp-id1545/ID-JHKDKHENNDHJSJ project/dep/emp-id8545/ID-GHFRDEEDEone string or two strings? I am asking since I don't know if I can use^projectsince^by default it will represent start of string, not start of line, so if there is someproject/emp-id...at start of second line^will prevent us from finding it.