简体   繁体   中英

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"... :(

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!");
}

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!");
}

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!");
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM