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

283
Visualizações
How to regex match words with/without hyphen

I'm having a lot of difficulties matching strings in JavaScript using regex. Problem is when I match strings like "assistant-attorney" with "attorney" it returns true. I cannot ignore/forbid hyphens, as I also want to be able to match "assistant-attorney" with "assistant-attorney" and also get true. Can't figure out if I should use word boundaries, or check if string does not start with white space or hyphen.

What I have so far is this:

([^-])(attorney)

Here's a test: https://www.regextester.com/?fam=121381

Hope anyone can help, thanks in advance.

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

0

I think you need to use word boundaries and enhance them with additional requirements:

(?<=^|[^-])\battorney\b(?=[^-]|$)
  • (?<=^|[^-]) - assert that behind me is the start of a line or is not a hyphen
  • \b - word boundary
  • attorney - the search term
  • \b - word boundary
  • (?=[^-]|$) - assert that in front of me is not a hyphen or is the end of a line

attorney - https://regex101.com/r/HCRKWi/1

assistant-attorney - https://regex101.com/r/2tvU1n/1

about 4 years ago · Juan Pablo Isaza Relatório

0

I think a simple Negative Lookbehind group could do the trick

(?<!-)attorney

Negative Lookbehind (?<!-) Assert that the Regex below does not match

UPDATE

As @MonkeyZeus said, the first version failed on attorneys and fakewordwithattorneyinit

The new regexp is using negative lookbehind and negative lookahead look like this :

\b(?<!-)attorney(?!-)\b if you want to match in all string enter image description here

^\b(?<!-)attorney(?!-)\b if you want to match "line begins with term"

https://regex101.com/r/FToha6/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