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

I'm just trying to create a regex to recognize image permissions in the file path.

An example input line might be something like "/path/to/file/2048x1556/file.type".

And all I want to be able to combine is the bit "/ 2048x1556".

I do not have to allow the number of permissions to change, but it should always be 3 or 4 characters long.

I have tried so far using:

Pattern.matches("/\\d+x\\d+", myFilePathString) 

What seems like 100 variations of this ... I'm new to regex, so I'm sure this is something simple that I'm missing, but I just can't figure it out.

Thanks in advance, Matt.

+4
source share
3 answers

You need to use the find method.

matches will try to match the string exactly .

find can match between strings if you are not using ^ , $

More on pattern.matcher () vs. pattern.matches () for more information


So your code will look 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(); 
+4
source

To determine if a file name contains permission:

 if (myFilePathString.matches(".*/\\d{3,4}x\\d{3,4}.*")) { // image filename contains a resolution } 

To extract permission in only one line:

 String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1"); 

Note that the extracted permission will be empty (not null ) if there is no permission in the file name, so you can extract it and then check for a space:

 String resolution = myFilePathString.replaceAll(".*/(\\d{3,4}x\\d{3,4}).*", "$1"); if (!resolution.isEmpty()) { // image filename contains a resolution } 
+4
source

If you want to use regex then

 import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String regular = "/path/to/file/2048x1556/file.type"; final String NAME_REGEX = ".*/path/to/file/([^/]+)/"; System.out.println(runSubRegex(NAME_REGEX, regular)); } private static String runSubRegex(String regex, String tag) { Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(tag); if (matcher.find()) { return matcher.group(1); } return null; } } 
+1
source

Source: https://habr.com/ru/post/1489293/


All Articles