-3

Given string "Neil, Gogte., Satyam, B.: Introduction to Java"

I need to extract only "Neil, Gogte." and "Satyam, B." from given string using regex how can I do it?

3 Answers3

0

You can use matcher to group

String str = "Neil, Gogte., Satyam, B.: Introduction to Java";
Pattern pattern = Pattern.compile("([a-zA-Z]+, [a-zA-Z]+\\.)");
Matcher matcher = pattern.matcher(str);

while(matcher.find()){
    String result = matcher.group();
    System.out.println(result);
}
Heng Lin
  • 96
  • 6
0

You can use the following regex to split the string. This matches any locations where ., exist:

(?<=\.),\s*
  • (?<=\.) Positive lookbehind ensuring what precedes is a literal dot character .
  • ,\s* Matches , followed by any number of whitespace characters

See code in use here

import java.util.*;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        final String s = "Neil, Gogte., Satyam, B.: Introduction to Java";
        final Pattern r = Pattern.compile("(?<=\\.),\\s*");
        String[] result = r.split(s);
        Arrays.stream(result).forEach(System.out::println);
    }
}

Result:

Neil, Gogte.
Satyam, B.: Introduction to Java
ctwheels
  • 21,901
  • 9
  • 42
  • 77
0

You might use this regex to match your names:

[A-Z][a-z]+, [A-Z][a-z]*\.

In Java:

[A-Z][a-z]+, [A-Z][a-z]*\\.

That would match

  • [A-Z] Match an uppercase character
  • [a-z]+ Match one or more lowercase characters
  • , Match comma and a whitespace
  • [A-Z] Match an uppercase character
  • [a-z]* Match zero or more lowercase characters
  • \. Match a dot

Demo Java

The fourth bird
  • 154,723
  • 16
  • 55
  • 70