-1
О.Г.дов.

I'm trying to match the "О.Г ." in this fragment. Normally, initials should be without spaces, so I need a regex that can account for optional spaces.

I've been using:

[А-Я]\s*\.\s*[А-Я]\s*\.\s*

But it seems to not match this correctly. I'm unsure why.Note, I am typing \\ in java before "s" and ".". Could someone spot an error?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
dj1121
  • 439
  • 1
  • 7
  • 16

1 Answers1

1

Regex to try:

"([А-Я]\\s*\\.\\s*[А-Я]\\s*\\.)\\s*.*"

Explanation and sample code:

If Matcher finds a match for given regex, you get rid of all unnecessary spaces in captured group #1 (in the parenthesis ()) and print it to the console:

String source = "О . Г . дов.";
Pattern p = Pattern.compile("(^[А-Я]\\s*\\.\\s*[А-Я]\\s*\\.)\\s*.*");
Matcher m = p.matcher(source);
if(m.find()) {
    String resultWithoutSpaces = m.group(1).replaceAll(" ", "");
    System.out.println(resultWithoutSpaces);
}

Output you get:

О.Г.
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • @dj1121 Glad that I could help - please have a look at my latest edit, I improved my answer to make it remove all unnecessary spaces from result initials. – Przemysław Moskal Feb 16 '18 at 23:14