Shazniq
Shazniq

Reputation: 453

Regex - Get string after last /, if that string contains something (user input)

Example strings:

storage/emulated/0/DCIM/Pictures/dog.jpeg (should be included)
storage/emulated/0/Vacation/Pictures/a-picture.jpg (shouldn't be included)
storage/emulated/0/Vacation/Pictures/mydog.jpg (should be included)

Example user input:

dog

(User input cannot contain /, \n, \r, \t, \0, \f, `, ?, *, \, <, >, |, ", :, %)

I need a regular expression that checks if the string after the last / contains the user input.

I know that getting the string after the last / is done with

([^/]+$)

but I don't know anything else about regex sadly, and even that I've found on internet. Is there anyone that can help?

Upvotes: 1

Views: 530

Answers (1)

anubhava
anubhava

Reputation: 785156

You may use this regex:

\S*/([^/\s]*dog\b\S*)

RegEx Demo

RegEx Details:

  • \S*/: Match longest match before last /. \S matches any non-whitespace character
  • (: Start capture group
    • [^/\s]*: Match 0 or more of any character that is not / and not a whitespace
    • dog\b: Match text dog ending with a word boundary
    • \S*: Match remaining string till end
  • ): capture group

Upvotes: 1

Related Questions