Reputation: 4418
I have a string like : String test = "A1=CA2=BOA2=RA4=OA11=O";
Now I want output like that : A1,A2,A2,A4,A11
If my string like :
String test = "[HEADER_1] [DATA] \n A10=T,(\"Re-N RO-25 M-N P-N (B)\"),1.0:0.8,R=25.0 F-7.829215,-4.032765 A20=B,R2,M=XY,R=29.999999999999996 F564.997550,669.454680";
public static void main(String[] args) {
String test = "A1=CA2=BOA2=RA4=O";
String data[] = test.split("[A-a]\\d{1,100}=");
for (String str : data) {
System.out.println("Split data:"+str);
}
}
What would be the regex for that?
Upvotes: 0
Views: 106
Reputation: 3268
I would not use split for that. The regex for the parts that you want is /a\d+/i
. If you use this and the Solution from Create array of regex matches to collect all matches in a list, you can easily create the desired output.
Converted the Regex in Java-Parlor:
public static void main(String[] args) {
String test = "A1=CA2=BOA2=RA4=OA11=O";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("(a\\d+)", Pattern.CASE_INSENSITIVE).matcher(test);
while (m.find()) {
allMatches.add(m.group());
}
}
allMatches now contains A1 A2 A2 A4 A11
Upvotes: 2
Reputation: 522741
String test = "A1=CA2=BOA2=RA4=OA11=O";
String[] parts = test.split("=");
String[] output = new String[parts.length];
for (int i=0; i < parts.length; ++i) {
output[i] = parts[i].replaceAll("^.*(A\\d*)$", "$1");
System.out.println(parts[i] + " becomes " + output[i]);
}
Output:
A1 becomes A1
CA2 becomes A2
BOA2 becomes A2
RA4 becomes A4
OA11 becomes A11
O becomes O
Upvotes: 0
Reputation: 7110
The regex you are probably looking for is [A-a][0-9]{1,2}
.
So in Java,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String test = "A1=CA2=BOA2=RA4=OA11=O";
Matcher m = Pattern.compile("[A-a][0-9]{1,2}").matcher(test);
while (m.find()) {
System.out.print(m.group(0)+",");
}
Upvotes: 0