I'm still in a very embryonic stage in Java and I am trying to figure out how to extract all specific values.
That are in this form (pattern) [A-H][1-8]
out of a String which length is unknown.
So for example if my string is " F5 F4 E3 "
I want to assign F5
to a variable, F4
to a variable, E3
to another variable.
Or if my string would be " A2 "
I would like to assign A2
to a variable.
I kind of have a feeling that I should use an Array
to store the values.
Please note that between the wanted pattern there are blank spaces "blankE2blank"
.
This is my code so far:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;
public class List {
public static void main(String[] args) {
int i = 0;
char[] Wanted = new char[]{?}; // What should I use here?
Pattern pat = Pattern.compile("\\s*d+\\s*D+\\s*d+");
String Motherstring = " F5 F4 E3 "; // this is just an example but the extraction should work for every string
Matcher m = pat.matcher(Motherstring);
while (pat.find()) {
Wanted[i] = pat; // ?
i++;
}
}
}
You may use \b
anchor. Below is hand-written example, I haven't test it. It just shows the idea.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;
public class List {
public static void main(String[] args) {
int i = 0;
char[] Wanted = new char[3];// Instead of array any dynamic collection should be used here. Since I'm not familiar with Java collections enough, Im leaving array here for correct work
Pattern pat = Pattern.compile("\\b\\w+\\b");
String Motherstring = " F5 F4 E3 ";
Matcher m = pat.matcher(Motherstring);
while (pat.find()) {
Wanted[i]= pat.group();
i++;
}
}
}