Reputation: 12704
I am trying to extract 14-A2F out of P‡GUID/CT-14-A2F2/SU-14-1F939(match til /
) or P‡GUID/CT-14-A2F2(match at the end of the line)
final Pattern pattern = Pattern.compile("CT-[a-zA-Z0-9-\\-]+(/|\\z)");
final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");
matcher.find();
matcher.group();
no success so far, is there something wrong with my pattern or I this is not the use case for matcher.group
Upvotes: 0
Views: 72
Reputation: 163642
In your regex CT-[a-zA-Z0-9-\\-]+(/|\\z)
you match CT-[a-zA-Z0-9-\\-]+
and then you use a capturing group for the last part which in this case will capture a forward slash. If you use matcher.group();
you will get the whole match which will be CT-14-A2F2/
You could shift the capturing group to the first part and then in the code refer to the first capturing group:
In Java:
CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)
final Pattern pattern = Pattern.compile("CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)");
final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");
matcher.find();
System.out.println(matcher.group(1)); // 14-A2F2
Upvotes: 1
Reputation: 101
This regex will match everything between two forward slashes. take the group out of it which is in parenthesis.
/([^/]*)/
you don't need to escape forward slash
Upvotes: 0