Reputation: 555
I have a string in which size of a particular media is given. I want to search size and print it.
sampleString = "Sample text having sample 4.5GB"
Note: string can have number of patterns such that [4.0GB, 4.0MB, 4GB, 70MB]
"GB" or "MB" could be integer or float.
My idea is to search the pattern like above mentioned in a string and then split it with MB or GB whichever is found and then grab the integer or float corresponding to that.
I have started finding patterns but code couldn't work. Below is my code:
public class CheckSize {
public static void main(String args[]) {
System.out.println(size("Sample text having sample 4.5GB"));
}
private static String size(String mString) {
Float size = 0f;
String mbSize = "";
String gbSize = "";
boolean found = mString.matches("\\d");
if (found) {
return "size available";
}
else {
return "size is not available";
}
}
}
Please help.
Upvotes: 0
Views: 58
Reputation: 521629
This problem is probably best handled by using a formal regex matcher. Here is a skeleton code showing you how you might approach it:
String line = "My first thumb drive stored 1.5GB, but second stored 1TB.";
String pattern = "\\b(\\d+(?:\\.\\d+)?)(?:MB|GB|TB)\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println("Found value: " + m.group(1) );
}
Found value: 1.5
Found value: 1
The basic idea here is that we can iterate over your text multiple times, pausing at each match, to print out the numbers preceding the storage size string.
Upvotes: 2