Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
How to write a RegEx that would capture a piece of a string, unless the string ends with a certain pattern?

I've started studying RegexOne, and there's a exercise in which we must capture a piece of a string until the "." , as long as the string ends with .pdf

match   file_a_record_file.pdf
match   file_yesterday.pdf
skip    testfile_fake.pdf.tmp   

But I wanted to get a bit deeper and capture this piece of a string, unless the string contains more than 3 characters after a dot character "."

I tried using

^(\w+(?!([.](.{4,}))$))

but of course it didn't work. How could I correct this pattern, considering the JavaScript RegEx library? (I don't want a function, only a pattern, if that's possible). I guess it would be more flexible if I could avoid using $, but I'd accept any answer matching the question. Thank you all in advance.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could check if there are no more than 4 non dot characters after a dot.

^(?!.*\.[^\.\n]{4})\w+(?:\.\w+)*$

Regex demo

const regex = /^(?!.*\.[^\.\n]{4})\w+(?:\.\w+)*$/;
[
  "file_a_record_file.pdf",
  "file_yesterday.pdf",
  "testfile_fake.pdf.tmp",
  "testfile_fake.docx.tmp"
].forEach(s => {
  console.log((regex.test(s) ? "Match: " : "No match: ") + s);
});

If you want the part before pdf if it should end on pdf, you can use a capture group and match .pdf at the end.

^(?!.*\.[^\.\n]{4})(\w+(?:\.\w+)*)\.pdf$

Regex demo

const regex = /^(?!.*\.[^.\n]{4})(\w+(?:\.\w+)*)\.pdf$/;
[
  "file_a_record_file.pdf",
  "file_yesterday.pdf",
  "testfile_fake.pdf.tmp",
  "testfile_fake.docx.tmp"
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    console.log(m[1]);
  }
});

about 4 years ago · Juan Pablo Isaza Report

0

I belive this is what you are trying to do:

mySting.match(/(.*)\.pdf$/)

Match   file_a_record_file.pdf
Match   file_yesterday.pdf
null    testfile_fake.pdf.tmp

Edit: the string without the extension is stored on mySting.match(/(.*)\.pdf$/)[1]

For the 3 characters match after the first dot

myString.match(/^([^\.]+)\.[\w]{1,3}$/);

Explanation: match everything that is not a dot + match the first dot + match a word that contains 1 to 3 characters at the end of string

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!