Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I match a Java regex on numbers and slashes (image resolution in a file path)

Tags:

java

regex

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.

like image 800
user2543067 Avatar asked Jan 13 '23 00:01

user2543067


2 Answers

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();
like image 168
Anirudha Avatar answered Feb 07 '23 05:02

Anirudha


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
}
like image 38
Bohemian Avatar answered Feb 07 '23 05:02

Bohemian