user17561857
user17561857

Reputation:

Regex - string contains after certain character

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

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

Upvotes: 0

Views: 1167

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 1

Yftach
Yftach

Reputation: 752

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

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

Upvotes: 0

Related Questions