'Extracting pattern from string with unknown length
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++;
}
}
}
Solution 1:[1]
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++;
}
}
}
Solution 2:[2]
Don't use an array. Use a List. The size is dynamic and allows you to add objects. See this:
Pattern pattern = Pattern.compile("[A-H][1-8]");
Matcher matcher = pattern.matcher(" F5 F4 E3 ");
// Create a new list (ArrayList) to store Strings.
ArrayList<String> list = new ArrayList<>();
// For every match of the regexp in the test string:
while (matcher.find())
// Add the match to the list.
list.add(matcher.group());
System.out.println(list);
Here is an online code demo. The STDOUT prints:
[F5, F4, E3]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Unihedron |
