我有固定格式的String
,这将是永远:SPXXX-SPYYY.zip从固定格式的字符串中提取数字
我需要从String
提取XXX和YYY,但如果例如XXX是003然后我想有和不是003。 (对于YYY也是如此)。
我已经写了这两段代码:
String st = "SP003-SP012.zip";
String[] splitted = st.split("\\.");
splitted = splitted[0].split("-");
splitted = splitted[0].split("P");
Integer in = new Integer(splitted[1]);
System.out.println(in); //Will print 3
//The same for the other part of the String
2.
Pattern pattern = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher matcher = pattern.matcher(st);
int num = 0;
while (matcher.find()) {
num = Integer.parseInt(matcher.group(1));
System.out.println(num);
}
- 为什么第二个代码只返回第一个数字? (XXX)错过了第二个?
- 什么代码更适合此目的?
你的第一个代码(分割)和第二个已经使用正则表达式! – Juvanis 2013-02-26 09:24:34
@Juvanis我误解了我自己:)修正。 – Maroun 2013-02-26 09:26:39