RagingLink
RagingLink

Reputation: 13

Regex statement to match parts of an URL

Let's say I have this string; https://cdn.discordapp.com/attachments/000000000000000000/000000000000000000/imagename.png

I currently have [^.]+$, but this only matches png and I would like to match image too. How would I go about doing this? Could it be possible to have one Regex statement, that matches image and png?

Upvotes: 1

Views: 46

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

Try this regular expression to math full name (example)

[^\/]+$

or this to match name without extension (example)

[^\/]+(?=\.png$)

explanation

  • [^\/]+ match any character except slash (in JS we can reduce this to [^/])
  • (?=\.png$) a positive lookahead which requires ".png" extension (and end of string $) after matched letters.

let s="https://cdn.discordapp.com/attachments/000000000000000000/000000000000000000/imagename.png";

console.log( s.match(/[^/]+$/)[0] )
console.log( s.match(/[^/]+(?=\.png$)/)[0] )

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163277

If you want to match image and png you could make use of 2 capturing groups and an anchor $ to assert the end of the string.

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

See the regex101 demo

Explanation

  • ([^/]+) Capturing group to capture the filename. Match 1+ times not a forward slash
  • .` Match a literal dot
  • ([^./]+) Capturing group to capture the extension. Match 1+ times not a dot or a forward slash
  • $ Assert the end of the string

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

If you want to only match imagename in your string use

[^/]+(?=\.[^/.]*$)

See the regex demo

If the extension can be optional use

[^/]+(?=(?:\.[^/.]*)?$)

See this regex demo

Note that depending on how you declare the regex you might need to escape / chars inside the patterns.

Details

  • [^/]+ - one or more chars other than / ([^/] is a (negated character class)
  • (?=(?:\.[^/.]*)?$) - a positive lookahead that requires the following patterns to match immediately to the right of the current location:
    • \. - a dot
    • [^/.]* - zero or more chars other than / and .
    • $ - end of string.

The (?:\.[^/.]*)? is an optional non-capturing group, the whole sequence of patterns inside is optional.

Upvotes: 1

Related Questions