我有一个字符串S =“AA AA BB:1 CC:2 DD:30 EE:149”;
如何循环使用字符串S并逐一抓取以下开头的每个数字:并将它们保存在Int?
E.g。
int holder;
String S = "AA AA BB :1 CC :2 DD :30 EE :149";
// Loop Start
holder = s.Grab1stnumberstarting with :
System.out.println(holder);
// Loop End
这样我得到了输出:
:1
:2
:30
:149
答案 0 :(得分:0)
尝试正则表达式
public static void main(String[] args) {
String s = "AA AA BB :1 CC :2 DD :30 EE :149";
Pattern p = Pattern.compile(":\\d+");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
O / P:
:1
:2
:30
:149
答案 1 :(得分:0)
您可以使用Positive Lookbehind
使用简单的正则表达式模式示例代码:
String s = "AA AA BB :1 CC :2 DD :30 EE :149";
Pattern p = Pattern.compile("(?<=:)\\d+");
Matcher m = p.matcher(s);
while (m.find()) {
int number = m.group()
System.out.println(":"+number);
}
正则表达式模式说明:
(?<= look behind to see if there is
: ':'
) end of look-behind
\d+ digits (0-9) (1 or more times (most possible))
答案 2 :(得分:0)
为了完成,并且为了避免现在有两个问题,这可以在不使用正则表达式的情况下轻松实现:
String s = "AA AA BB :1 CC :2 DD :30 EE :149";
String[] parts = s.split(" ");
for(String part : parts) {
if(part.startsWith(":")) {
System.out.println(part);
}
}
这假设所需的输出是以:
开头的任何内容,而不仅仅是数字,但可以轻松提升以仅查找数字。