Reputation: 3558
I need help creating a regular expression. Here are two sample strings:
/path/to/file.jpg
/path/to/file.type.jpg
Respectively, I'm trying to capture:
file.jpg
file.type.jpg
But I want to capture the three as separate strings.
file,jpg
file,type,jpg
Note that I'm not capturing the periods. I thought something like this could work (excluding the new lines):
([a-z]+)\.
[([a-z]+)[\.]{1}]?
([a-z]{3})
Guidance would be appreciated. I'm wondering if there is another modified I would need to use to have it capture it properly.
The above expression errors out, by the way :(
Upvotes: 0
Views: 92
Reputation: 43673
I suggest you to use pattern
\/([^.]+)\.?([^.]+|)\.([^.]+)$
and you will have 3 groups: file, type (which will be empty, if not present) and extension
Upvotes: 1
Reputation: 1830
You can use: "\/(?:\w+\/)+(\w+)\.?(\w+)?\.(\w+)"
as regex.
Edit: didnt read about not matching dots.
Live Demo
Upvotes: 1
Reputation: 13702
You'd have to use:
/(\w+)(\.(\w+))?\.(\w+){3,4}\b
Then capturing groups 1, 3 and 4 would be your: file(1) type(3) and jpg/png whatever(4)
Groups taken apart:
(\w+)
- matches word characters 1 or more (equivalent of saying: {1, }
(\.(\w+))?
- matches the 3rd group and with a dot in front, and makes the whole group optional ( ?
)(\w+)
- as gr 1(\w{3,4})\b
- matchees 3 or 4 word characters ( {3,4}
) and ensures that after those chracters there are no other characters (word end - \b
- ! if supported !)Upvotes: 1