Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

^(\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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading