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

119
Visualizações
Regex for last capital letter in string

I have a regular expression implemented in javascript that checks for all capital letters in a string:

.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g)

then adds a space by .join(" ")

–

How can I write a regular expression that finds only the last capital letter instead, then joins a space before that letter? Thanks for your help.

—

Sample Input: "HelloMyNameIsNick"

Ideal Output: "HelloMyNameIs Nick"

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

To add a space before the last uppercase letter, greedily match all followed by a single uppercase letter:

"ABCabcABC".replace(/(.*)([A-Z])/, "$1 $2")
"ABCabcAB C"

To add a space before the last uppercase letter for each uppercase sequence, match an uppercase letter that is not followed by another uppercase letter:

"ABCabcAB".replaceAll(/([A-Z](?![A-Z]))/g, " $1")
"AB CabcA B"
about 4 years ago · Juan Pablo Isaza Relatório

0

Update

'HelloMyNameIsNick'.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2')

Test cases:

console.log(`
HelloMyNameIsNick
Hello
 Hello
HELLO
HellO
HeLLo
Hello Test
HELLO TEST
hello test
HELLO 1$@(😎-.aa
HELLO 1$@(😎-.Aa
`.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2'))

Check out test cases which are handled properly:

Hello
 Hello 
Hello Test

Old answer that only finds last uppercase

What you are looking for is

/[A-Z](?!.*[A-Z].*)/gm

Playground with tests

It finds only the last capital letter.

If you want to find last letter in whole text instead on each line you can replace m (multiline) to s (single line):

/[A-Z](?!.*[A-Z].*)/gs

Playground with tests

*Note / /s flag may not be supported in all browsers.

(?!ABC) refers to negative lookahead. It checks conditions in expression but not includes them in the final result. More info

about 4 years ago · Juan Pablo Isaza Relatório

0

Use a non-greedy quantifier:

/[A-Za-z]*?([A-Z])[^A-Z]*/

I suggest you add beginning and end anchors to make sure that you are matching the entire string, otherwise the pattern will segment strings:

/^[A-Za-z]*?([A-Z])[^A-Z]*$/

Try it out here: https://regex101.com/r/h9Acm6/1

about 4 years ago · Juan Pablo Isaza 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