Reputation: 11
So i need a help to find certain word in the given string. So I've made a string and used a for loop to get the word i want, but it doesn't seem to be working, I only want to get the 2019
out of the string.
public void wStart() throws Exception {
String folder = "file/print/system/2019/12 - December";
String[] folderSplit = folder.split("/");
for (int i=3; i < folderSplit.length; i++) {
String folderResult = folderSplit[i];
System.out.println(folderResult);
}
}
Upvotes: 1
Views: 128
Reputation: 194
You can try this method, which I just added a statement that compares loop values with the string:
public static void wStart() throws Exception
{
String folder = "file/print/system/2019/12 - December";
String[] folderSplit = folder.split("/");
for(int i = 3; i < folderSplit.length; i++)
{
if(folderSplit[i] == "2019"){
String folderResult = folderSplit[i];
System.out.println("Excepted "+folderResult);
}else{
String folderResult = folderSplit[i];
System.out.println("Not Excepted "+folderResult);
}
}
}
Upvotes: -1
Reputation: 27723
If we only wish to get the year in a string with no other four digits number, we would be simply using this expression:
(\d{4})
or we would add additional boundaries, such as:
\/(\d{4})\/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(\\d{4})";
final String string = "file/print/system/2019/12 - December";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
jex.im visualizes regular expressions:
Upvotes: 5
Reputation: 520908
If the year would always be the second to last path element, then just access that element:
String folder = "file/print/system/2019/12 - December";
String[] parts = folder.split("/");
String year = parts[parts.length-2];
If instead the year could be any path element, then we can try fishing it out:
String year = folder.replaceAll(".*\\b(\\d{4})\\b.*", "$1");
Upvotes: 3