String weapon = "pistol . <1/10>";
Result:
int clip = 1;
int ammo = 1;
字符串格式 = (WEAPON) 。<(CLIP)/(AMMO)>
我需要 Clip 和 Ammo 值。
那么我如何提取字符串的这两个值。我可以用“/”分割它,因为它仍然会面对:“gun <1”和“10>”
提前谢谢
您可以像这样删除非数字字符:
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+")
拆分非数字字符(在本例中为/
and >
)并忽略尾随的空字符串(如果有)或者,如果格式始终与您在问题中提到的完全一样,您可以查找该特定模式:
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
}
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
完毕..
你也可以试试这个...
从字符串 "(WEAPON) . <(CLIP)/(AMMO)>" 中提取值 WEAPON、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));
}
从字符串“pistol . <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("/"));
}
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));
然后你分别用“<”(枪<1)和“>”(10>)分割结果子串
你可以尝试这样的事情。
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