我有一个字符串,12-512-2-15-487-9-98
,我想分成两个字符串,如下所示:
str1="12-512-2";
str2="15-487-9-98";
这意味着第一个字符串将包含第三个-
之前的字符,第二个字符串将包含其后的其余字符。
我该怎么做?我尝试使用split("-")
和concatstr[0]+"-"+str[1]+"-"+str[2]
但我想要更简单的答案。
String text = "12-512-2-15-487-9-98";
int pos = text.indexOf('-', 1 + text.indexOf('-', 1 + text.indexOf('-')));
String first = text.substring(0, pos);
String second = text.substring(pos+1);
System.out.println(first); // 12-512-2
System.out.println(second); // 15-487-9-98
String line = "12-512-2-15-487-9-98";
String pattern = "(\\d+-\\d+-\\d+)-(\\d+-\\d+-\\d+-\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
想要的是m.group(1)
和m.group(2)
的值。
int indexofSecondOccurance = str.indexOf(“-”,str.indexOf(“-”)+1);int finalIndex = str.indexOf(“-”,indexofSecondOccurance + 1));
之后,您可以用substring()分割字符串。