Reputation: 719
I have the following String line:
dn: cn=Customer Management,ou=groups,dc=digitalglobe,dc=com
I want to extract just this from the line above: Customer Management
I've tried the following RegEx expression but it does quite do what I want:
^dn: cn=(.*?),
Here is the java code snippet that tests the above expression:
Pattern pattern = Pattern.compile("^dn: cn=(.*?),");
String mydata = "dn: cn=Delivery Admin,ou=groups,dc=digitalglobe,dc=com";
Matcher matcher = pattern.matcher(mydata);
if(matcher.matches()) {
System.out.println(matcher.group(1));
} else {
System.out.println("No match found!");
}
The output is "No match found"... :(
Upvotes: 0
Views: 62
Reputation: 844
Please use below code:
@NOTE: instead of using matches you have to use find
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^dn: cn=(.*?),");
String mydata = "dn: cn=Delivery Admin,ou=groups,dc=digitalglobe,dc=com";
Matcher matcher = pattern.matcher(mydata);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("No match found!");
}
}
Upvotes: 0
Reputation: 11553
Your problem is that the matcher want to match the whole input. Try adding a wildcard to the end of the pattern.
Pattern pattern = Pattern.compile("^dn: cn=(.*?),.*");
String mydata = "dn: cn=Delivery Admin,ou=groups,dc=digitalglobe,dc=com";
Matcher matcher = pattern.matcher(mydata);
if(matcher.matches()) {
System.out.println(matcher.group(1));
} else {
System.out.println("No match found!");
}
Upvotes: 0
Reputation: 963
Your regex should work properly, but matches
attempts to match the regex to the entire string. Instead, use the find
method which will look for a match at any point in the string.
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("No match found!");
}
Upvotes: 2