I'm just trying to create a regex to recognise image resolutions in a file path.
An example input string could be something like "/path/to/file/2048x1556/file.type".
And all i want to be able to match on is the "/2048x1556" bit.
I should not that the numbers of the resolutions can change, but will always be either 3 or 4 characters in length.
I've tried so far using:
Pattern.matches("/\\d+x\\d+", myFilePathString)
An what feels like about 100 variations on that... I'm new to regex's so I'm sure it's something simple that I'm overlooking but I just can't seem to figure it out.
Thanks in advance, Matt.
You need to use find method..
matches
would try to match the string exactly.
find
could match in between the string provided you don't use ^
,$
See pattern.matcher() vs pattern.matches() for more info
So,your code would be like
boolean isValid=Pattern.compile(yourRegex).matcher(input).find();
But if you want to extract:
String res="";
Matcher m=Pattern.compile(yourRegex).matcher(input);
if(m.find())res=m.group();
To determine if the filename contains a resolution:
if (myFilePathString.matches(".*/\\d{3,4}x\\d{3,4}.*")) {
// image filename contains a resolution
}
To extract the resolution in just one line:
String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1");
Note that the extracted resolution will be blank (not null
) if there is no resolution in the filename, so you could extract it, then test for blank:
String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1");
if (!resolution.isEmpty()) {
// image filename contains a resolution
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With