JamesD
JamesD

Reputation: 719

How do I extract substring from this line using RegEx

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

Answers (3)

GauravRai1512
GauravRai1512

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

Roger Lindsjö
Roger Lindsjö

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

Wrokar
Wrokar

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

Related Questions