Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split file extention using regex

Tags:

regex

php

how to split with regex from asddhj123.png.png to 123.png

I have tried with regex below, but the first extension still involved :(

 /[a-zA-z.]|\.(jpg|png)$/

i hope that will be return :

asdasd123.jpg.jpg => 123.jpg

dsds345.png.png => 345.png

like image 575
Ridwan Maulana Tanjung Avatar asked Aug 27 '26 13:08

Ridwan Maulana Tanjung


1 Answers

This expression is likely to return the desired outputs:

(?i)\d+\.(?:jpe?g|png)

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


const regex = /\d+\.(?:jpe?g|png)/gmi;
const str = `asdasd123.jpg.jpg => 123.jpg
asdasd123.jpeg.jpeg => 123.jpeg
dsds345.png.png => 345.png

`;
let m;

while ((m = regex.exec(str)) !== null) {
	if (m.index === regex.lastIndex) {
		regex.lastIndex++;
	}

	m.forEach((match, groupIndex) => {
		console.log(match);
	});
}
like image 156
Emma Avatar answered Aug 29 '26 03:08

Emma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!