Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
Grab the second number and the word after it using regexp

I have a string:

str = "1 - hello world 1234 abc 5678 def"

I want to grab 1234 abc from the string.

My current implementation str[/\d+\s*\D*$/] only grabs the last number with the word.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use

str[/\d+\D+(\d+\s*\w+)/, 1]
str[/\d+\D+\K\d+\s*\w+/]

See this regex demo and this regex #2 demo.

Here, only the first regex match is searched for. Details:

  • \d+ - one or more digits
  • \D+ - one or more non-digits
  • (\d+\s*\w+) - Group 1: one or more digits, zero or more whitespaces, and one or more word chars
  • \K - match reset operator that discards all text matched so far.

NOTE:

  • If a "word" is a chunk of non-whitespace chars, replace \w+ with \S+
  • If you want to support float values (numbers with fractional parts), you will need to replace \d+ with \d*\.?\d+ or \d+(?:\.\d+)? patterns.

Here is a Ruby test:

str = "1 - hello world 1234 abc 5678 def"
puts str[/\d+\D+(\d+\s*\w+)/, 1]
# => 1234 abc
puts str[/\d+\D+\K\d+\s*\w+/]
# => 1234 abc
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda