Java 在字符串中获取字符串
所以我有这个字符串:Java 在字符串中获取字符串,java,string,Java,String,所以我有这个字符串: String myString = "Welcome, your drive today to the LAX will be (45+ min). Enjoy your drive!"; 获取45作为单独字符串的最佳方法是什么?这个字符串有时可能包含多个数字,例如: String myString=“欢迎,您今天到洛杉矶国际机场的车程为(45分钟以上)。您应该在(上午11:10)左右到达。祝您旅途愉快!” 但是我只想得到一个45+min的字符串,并将+min分开,这样4
String myString = "Welcome, your drive today to the LAX will be (45+ min). Enjoy your drive!";
获取45
作为单独字符串的最佳方法是什么?这个字符串有时可能包含多个数字,例如:
String myString=“欢迎,您今天到洛杉矶国际机场的车程为(45分钟以上)。您应该在(上午11:10)左右到达。祝您旅途愉快!”
但是我只想得到一个45+min的字符串,并将
+min
分开,这样45
就是我唯一的字符串。这可以用。
正则表达式的Java预定义字符类。
. = 任何字符(可能与行终止符匹配,也可能不匹配)
\d=一位数字:[0-9]
\D=非数字:[^0-9]
String myString = "Welcome, your drive today to the LAX will be (45+ min). Enjoy your drive!";
//Replace all non digit characters with empty space so only numbers will be there.
myString = myString.replaceAll("\\D", "");
System.out.println(myString); //this displays only numbers.
所以,经过反复试验,我终于找到了答案。如果你有更好的方法,请评论,我不介意改变我接受的答案
String text = "Welcome, your drive today to the LAX will be (45+ min) and the tolls will cost ($2.50). Enjoy your drive!";
tripMiles = getNumberFromString("(?i)(\\d+)\\s+ min", text);
public static double getNumberFromString(String value, final String s)
{
double n = 0.0;
Matcher M = Pattern.compile(value).matcher(s);
while (((Matcher)M).find())
{
try {
n = Double.parseDouble(((Matcher)M).group(1));
if (debug) Log.v(TAG, "Number is : " + ((Matcher)M).group(1));
}
catch (Exception ex) {
n = 0.0;
}
}
return n;
}
indexOf(“45”)
?子串?或者这个数字会改变吗?不同的单位?如果是这样的话,Regex?Regex似乎是您的最佳选择,因为字符串的其余部分已修复,或者还有其他变量吗?System.out.println(myString.replaceAll(“.+\(\\d+).+\.+”,“$1”)代码>myString.replaceAll(“\\D”和“)代码>;)所以,如果字符串中每隔一个数字,这个方法就不起作用了?示例:String myString=“欢迎光临,您今天到洛杉矶国际机场的车程为(45分钟以上),过路费为($2.50)。祝您旅途愉快!”
那么您的方法会将两个数字返回到一个字符串中吗?@Jayce这就是为什么您需要更精确地满足您的需求。只要看看您的示例,str=“45”
就足够了。如果你想要一个灵活的解决方案,你需要描述你试图匹配的模式。