Home > Net >  Regex - string contains after certain character
Regex - string contains after certain character

Time:01-21

My use case is "www.example.com/myimage.jpg".

I need a regex to check that after the last occurrence of "/", the string contains a "."

Have tried this but it doesn't work for the "." check

/([^\/] $)[^.]/

CodePudding user response:

You could write the pattern matching the last occurrence of / and then match a dot between all characters except / until the end of the string.

Note that [^\/] can also match a newline, and if you don't want to match a newline you could write it as [^\/\r\n]

If the delimiter is different than a forward slash you don't have to escape it.

^.*\/[^\/\n.]*\.[^\/\n]*$

The pattern matches:

  • ^ Start of string
  • .* Match the rest of the line
  • \/ Match /
  • [^\/.]*\.[^\/]* Match a dot between optional chars other than / or .
  • $ End of string

Regex demo

CodePudding user response:

\/[^\/]*\.[^\/]*$

This should work.

What this regex is doing is finding a \ character, then trying to find a string with a dot in it until you reach the end of the input. The trick is to not find anymore \ characters using [^/]. Which will match any character except \

This way we make sure this is the last \ character

  •  Tags:  
  • Related