Dog
Dog

Reputation: 2906

Regex for if a character exists after the last instance of a character

I'm trying to put together a regex that will indicate whether a character exists after the last instance of a character in a string. For example, the regex would return a match if a period '.' appeared after the last instance of a '/'

So far I am able to find the string combination for the final part of the string after the / using:

   [^\/]+$

But I am not sure how to only return a match if a period '.' is included in that final string portion. I greatly appreciate any help.

I realize it would be possible to do this by splitting the string, but I was hoping a pure regex way existed.

Upvotes: 3

Views: 113

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

You can use

/[^\/.]*\.[^\/]*$/       // The whole match is the required result
/.*\/([^\/.]*\.[^\/]*)$/ // and extract Group 1 contents

See the regex demo #1 and regex demo #2.

The second one is more efficient in practice, as the part after last / is usually closer to the end of a longer string, and the match is usually obtained faster.

Details

  • [^\/.]* - zero or more chars other than . and /
  • \. - a dot
  • [^\/]* - zero or more chars other than /
  • $ - end of string.

JavaScript demo:

const texts = [ 'a/b/c', 'a/b/c.a' ];
texts.forEach( text => {
    console.log( text, '(/[^\/.]*\.[^\/]*$/) =>', (text.match(/[^\/.]*\.[^\/]*$/)?.[0] || "No match") );
    console.log( text, '(/(.*\/([^\/.]*\.[^\/]*)$/) =>', (text.match(/.*\/([^\/.]*\.[^\/]*)$/)?.[1] || "No match") );
  }
)

Upvotes: 1

Related Questions