String 1 = 3 "Hold Gear" 2 "Min Gear Request" 1 "Max Gear Request" 0 "No Action" ;
String 2 = 7 "Driver Disabled" 6 "Enhanced Operation" 5 "Calibrating" 4 "Warming Up" 3 "Permanently Failed" 2 "Temporarily Inhibited" 1 "Reduced Function" 0 "Normal Operation" ;
求一个方法。能够将1 截取为
{3 "Hold Gear",2 "Min Gear Request",1 "Max Gear Request",0 "No Action"}
的数组
同时可以将2 截取为
{ 7 "Driver Disabled", 6 "Enhanced Operation",5 "Calibrating" ,4 "Warming Up", 3 "Permanently Failed", 2 "Temporarily Inhibited" ,1 "Reduced Function" 0 "Normal Operation"}
的数组
也就是说后面字符串长度不定, 能不能通过一个算法实现。要是能用正则表达式就更好了
Java String 算法 正则表达式 函数
------解决方案--------------------
regex=".*?(\\d{1} \\"\\w+\\")";
差不多正则就是这样,
------解决方案--------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestReg {
public static void main(String[] args) {
String str1 = "3\"Hold Gear\"2\"Min Gear Request\"1\"Max Gear Request\"0\"No Action\"" ;
//String 2 = 7 "Driver Disabled" 6 "Enhanced Operation" 5 "Calibrating" 4 "Warming Up" 3 "Permanently Failed" 2 "Temporarily Inhibited" 1 "Reduced Function" 0 "Normal Operation" ;
//System.out.println(Arrays.toString(str1.split("^\\d(\\w+)$")));
Matcher m = Pattern.compile("(\\d)([(a-zA-Z)(\\\")\\s])+").matcher(str1);
while(m.find()){
System.out.print(m.group()+" ");
}
}
}
结果:3"Hold Gear" 2"Min Gear Request" 1"Max Gear Request" 0"No Action"