Get only the first name, after space using Java

1

Good afternoon.

I have the following String:

  

"Carlos Ferreira da Silva"

I wanted to get only the first name and ignore rest after the "space".

Using regular expressions, how could I do this?

    
asked by anonymous 07.03.2017 / 21:45

2 answers

4

Just use the \S+ pattern

Example:

import java.util.*;
import java.util.regex.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
      String linha = "João Ferreira da Silva";
      String pattern = "\S+";

      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(linha);
      if (m.find( )) {
        System.out.println(m.group(0) );
      }
    }
}

Output:

  

John

See the Ideone .

According to documentation , \S matches with non-space characters and + serves to get the characters until the condition is no longer satisfied.

    
07.03.2017 / 21:53
1

Using regular expressions you can get the first name with the regex ^([a-zA-ZÈ-Úè-ú]+)\s we can only get the first name:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

   public static void main( String args[] ) {
      // String com texto a ser verificado
      String texto = "André Carlos Ferreira da Silva";
      // Expressão regular a ser usada
      String pattern = "^([a-zA-ZÈ-Úè-ú]+)\s";
      // Inicialização de RegExp Pattern
      Pattern r = Pattern.compile(pattern);
      // Inicialização do verificador de pattern em texto
      Matcher m = r.matcher(texto);

      // Se (matcher encontrou regexp na string)
      if (m.find()) {
         // escreva o grupo encontrado
         System.out.println("Olá, " + m.group(0) );
      } else {
         // mensagem de erro
         System.out.println("Você não tem mais de um nome?");
      }
   }
}

You can easily test regular expressions using Regex101 , this expression is registered at link

Demonstration

    
07.03.2017 / 21:55