String weapon = "pistol . <1/10>";
Result:
int clip = 1;
int ammo = 1;
字符串的格式=(WEAPON)。 <(CLIP)/(AMMO)>
而我需要Clip和Ammo值。從字符串中提取2個整數
所以我如何可以提取這兩個值的字符串。預先
String weapon = "pistol . <1/10>";
Result:
int clip = 1;
int ammo = 1;
字符串的格式=(WEAPON)。 <(CLIP)/(AMMO)>
而我需要Clip和Ammo值。從字符串中提取2個整數
所以我如何可以提取這兩個值的字符串。預先
您可以刪除非數字字符,像這樣:
String s = "pistol . <1/10>";
String[] numbers = s.replaceAll("^\\D+","").split("\\D+");
現在numbers[0]
是1
和numbers[1]
是10
。
s.replaceAll("^\\D+","")
在字符串的開頭刪除非數字字符,所以新的字符串是現在"1/10>"
.split("\\D+")
拆分非數字字符(在這種情況下/
和>
),並忽略尾隨空字符串,如果任何或者,如果格式總是完全按照你在你的問題中提到,你可以尋找特定patte RN:
private final static Pattern CLIP_AMMO = Pattern.compile(".*<(\\d+)/(\\d+)>.*");
String s = "pistol . <1/10>";
Matcher m = CLIP_AMMO.matcher(s);
if (m.matches()) {
String clip = m.group(1); //1
String ammo = m.group(2); //10
}
謝謝,是否有可能獲得武器的名稱?我得到了2個整數和1個字符串) – user1621988 2013-03-20 14:24:03
@ user1621988用第二種方法,例如:'Pattern p = Pattern。編譯(「\\ b(\\ w +)\\ b。* <(\\ d +)/(\\ d +)>。*」);'會工作。武器將是'm.group(1)',剪輯將是'm.group(2)'和彈藥'm.group(3)'。 – assylias 2013-03-20 14:26:07
「槍< 1」和「10>」
感謝和則u由「<」(槍< 1)分割所得子: 我可以通過「/」通過將它分割它仍將面臨和 「>」(10>)分別
String weapon = "pistol . <1/10>";
String str = weapon.substring(weapon.indexOf("<")+1,weapon.indexOf(">")); // str = "<1/10>"
int clip = Integer.parseInt(str.substring(0,str.indexOf("/"))); // clip = 1
int ammo = Integer.parseInt(str.substring(str.indexOf("/")+1)); // ammo = 10
夾= 1
彈藥= 10
完成..
你可以試試這個太...
提取從字符串「(武器)的值支招,CLIP和彈藥。 <(CLIP)/(AMMO)> 「
String str = "(WEAPON) . <(CLIP)/(AMMO)>";
Pattern pattern = Pattern.compile("\\((.*?)\\)");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
解壓縮的值1,10從字符串」 手槍。 < 1/10>「:
List<String[]> numbers = new ArrayList<String[]>();
String str = "pistol . <1/10>";
Pattern pattern = Pattern.compile("\\<(.*?)\\>");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
numbers.add(matcher.group(1).split("/"));
}
你可以嘗試這樣的事情
public static void main(String[] args) {
String weapon = "pistol . <1/10>";
String test = "";
Pattern pattern = Pattern.compile("<.*?>");
Matcher matcher = pattern.matcher(weapon);
if (matcher.find())
test = matcher.group(0);
test = test.replace("<", "").replace(">", "");
String[] result = test.split("/");
int clip = Integer.parseInt(result[0]);
int ammo = Integer.parseInt(result[1]);
System.out.println("Clip value is -->" + clip + "\n"
+ "Ammo value is -->" + ammo);
}
輸出:
Clip value is -->1
Ammo value is -->10
String weapon = "pistol . <1/10>";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(weapon);
List<Integer> numbers = new ArrayList<Integer>();
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
System.out.println("CLIP: " + numbers.get(0));
System.out.println("AMMO: " + numbers.get(1));
http://docs.oracle.com/ javase/1.5.0/docs/api/java/lang/String.html#substring(int,int) – rajesh 2013-03-20 14:05:39