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

344
Visualizações
Javascript: write condition regex for multiple strings

I want to write a regex for the following strings to include all strings:

B9966
ch6258
028
chIRZ170
IRZ170

B8966A
BA966C

The OUTPUT should be as follows:

966
6258
028
170
170

966A
BA966C

Conditions:

  1. If you look at b9966, you see that its output is 966. it means If the string started with one character, the next digit of the character is not part of the output.
  2. If the string is an integer, the whole string is output.
  3. I want the output of B8966A to be like this 966A.
  4. Otherwise, if the previous three conditions do not exist, all string digits are returned as output.

I wanted to write with conditions in regex (ie: (?(?condition)then|else)) but found that javascript does not support conditions.

For example, the following solution works fine, but I'm looking for a more professional regex:

^\d+.|(?<=^\D{1}\d)\d+.|(?<=^\D{2,})\d+.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For your example data, you can remove either an uppercase case followed by a single digit, or remove all non digits.

[A-Z]\d|[^\d\n]+

Regex demo

const regex = /[A-Z]\d|[^\d\n]+/g;
[
  "B9966",
  "ch6258",
  "028",
  "chIRZ170",
  "IRZ170"
].forEach(s => console.log(s.replace(regex, '')));

Edit

For the updated examples, you could start the match with a non digit followed by a digit, or match 1+ non digits:

\b(?:[^\d\n]\d|[^\d\n]+)

Regex demo

To not touch the last example, you can use a negative lookahead:

\b(?:[^\d\n]\d|(?![A-Z]{2}\d)[^\d\n]+)

Regex demo

const regex = /\b(?:[^\d\n]\d|(?![A-Z]{2}\d)[^\d\n]+)/;
[
  "B9966",
  "ch6258",
  "028",
  "chIRZ170",
  "IRZ170",
  "B8966A",
  "BA966C"
].forEach(s => console.log(s.replace(regex, '')));

about 4 years ago · Juan Pablo Isaza Relatório

0

Another regex can be used:

(?<!^\D)\d+.*

In the above regex, the Negative Lookbehind is used, ie if each character did not start with \D before and is matched with the character \d after.
Result: https://regex101.com/r/Av8pEq/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