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

172
Visualizações
Using regex to place dashes at specific indexes of a string containing numbers and letters

So the formatted code needs looks like this:

"US-XXX-12-12345"

So that's two letters, followed by 3 letters/numbers, followed by 2 numbers, then followed by 5 letters/numbers. I was able to get it to work using only numbers with the following:

return testString
  .replace(/(\d{2})(\d)/, '$1-$2')
  .replace(/(\d{3})(\d)/, '$1-$2')
  .replace(/(\d{2})(\d{2})/, '$1-$2')
  .replace(/(\d{4})(\d{2})/, '$1-$2')

This returns:

"12-345-67-89012" 

I tried switching the lowercase d's for uppercase ones (representing letters) and it adds all sorts of extra dashes and does not let me backspace. Any and all help is much appreciated!

EDIT: Ended up solving it like this:

const clean = new RegExp(/[^a-zA-Z0-9]/, 'gi')

return testString
    .replace(clean, '')
    .replace(/([a-zA-Z0-9]{2})([a-zA-Z0-9])/, '$1-$2')
    .replace(/(-[a-zA-Z0-9]{3})([a-zA-Z0-9])/, '$1-$2')
    .replace(/(-[a-zA-Z0-9]{3})(-[a-zA-Z0-9]{2})([a-zA-Z0-9])/, '$1$2-$3')

Thanks to all who tried to help, I really appreciate it <3

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

0

I would use a function like this:

function mask(string, model){
    let i = 0;
    return model.replace(/#/g, () => string[i++] || "");
}

use:

mask("USXXX1212345", "##-###-##-#####") => 'US-XXX-12-12345'

the first parameter of the function is the string you want to format, and the next parameter is how it will be formatted

about 4 years ago · Juan Pablo Isaza Relatório

0

This isn't quite what you asked for but regex probably isn't the best solution to this question. A better option would probably be to use something like react-input-mask because you mentioned using this in real time in a React form.

import { useState } from "react";
import InputMask from "react-input-mask";

const Example = () => {
  const [inputText, setInputText] = useState("");

  return (
    <InputMask
      mask="aa-***-99-*****"
      value={inputText}
      onChange={(e) => setInputText(e.target.value)}
    />
  );
};

And here's a CodeSandbox example because I can't for the life of my embed a functional example in a SO answer: https://codesandbox.io/s/react-input-mask-example-554lcn?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Relatório

0

If the string is known to have the correct pattern, you can replace matches of the following regular expression with a hyphen.

(?<=^.{2})|(?<=^.{5})|(?<=^.{7})

If lowercase letters are permitted the case-indifferent flag (i) needs to be set.

This expression contains an alternation comprised of three positive lookbehind expressions. It reads, "match the position following the second, fifth or (|) seventh character of the string. Think of (?<=^.{2}) as matching the location between the second and third character of the string. Because it does not match any characters it is referred to as a zero-width match.

Demo


If the string is not known to have the correct pattern, I suggest the string be first matched against the following regular expression to confirm its pattern is correct.

 ^[A-Z]{2}[A-Z\d]{3}\d{2}[A-Z\d]{5}$

Demo

This regular expression (with the case-indifferent flag is set) can be broken down as follows.

^           # match the beginning of the string
[A-Z]{2}    # match two letters
[A-Z\d]{3}  # match three letters or digits
\d{2}       # match two digits
[A-Z\d]{5}  # match five letters or digits
$           # match end of string

The first regular expression can be modified to also confirm that the string has the correct pattern but it complicates the expression considerably. If you would like to see that please let me know.

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