Only get the first name, after space using Java

Asked

Viewed 1,793 times

1

Good afternoon.

I got the following String:

"Carlos Ferreira da Silva"

I wanted to take just the first name and ignore rest after the "space".

Using regular expressions, how could I do that?

  • 2

    Do you really need regex? You can do this without using regex and it’s much simpler.

  • 1

    @diegofm agree...

  • Sorry for commenting on an answered question, but you can make it much simpler through the method split(""), class String. Just write that line: String primeiroNome = "Carlos Ferreira da Silva".split(" ")[0];. The method split(" ") separates into an array of Strings a String delimited by the character passed as parameter. In our case the space. Already in return of this method we inform that we want the first position through [0] and ready. :-)

2 answers

4


Just you use the pattern \\S+

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

Exit:

John

See on Ideone.

According to the documentation, the \\S matches characters other than spaces and the + serves to take the characters until the condition is no longer satisfied.

  • 1

    The \\w makes match with accented characters?

  • @Rômulogabrielrodrigues no, I looked at the example and I didn’t think about this condition

  • 1

    I ended up remembering a similar example in this question http://answall.com/a/27846/3117

  • I tried using "José" and really does not do with accented characters. But the tip is excellent, well dry the code.

  • @Amandarj I changed the example, I think the \\S+ better addresses the issue

  • @Math thanks. It’s perfect for what I need. Thank you so much!!!

  • 1

    You could have kept the same code and changed the Pattern for \\p{L}+ or \\p{IsLatin}+.

  • @Felipemarinho Poisé, has several ways of doing, as the question not specific a clear way ends up giving room for several answers, as I believe it is a simple application and maybe even didactically I think that there will be other Charsets in the text I think the S should meet :) but really your suggestion is good for real situations

Show 3 more comments

1

Using regular expressions you can take the first name with regex ^([a-zA-ZÈ-Úè-ú]+)\s we can only take 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 the Regex101, this expression is registered in https://regex101.com/r/lVvPcx/1

Demonstration

Browser other questions tagged

You are not signed in. Login or sign up in order to post.