Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

javascript - 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.

question from:https://stackoverflow.com/questions/65891518/regex-for-if-a-character-exists-after-the-last-instance-of-a-character

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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") );
  }
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...