如何从字符串中获取数值和非数值
How to obtain numeric and non-numeric values from a String
假设有三个字符串:
String s1 = "6A";
String s2 = "14T";
String s3 = "S32";
我需要提取数值(即 6、14 和 32)和字符(A、T 和 S)。
如果第一个字符始终是数字,则此代码有效:
int num = Integer.parseInt(s1.substring(0,1));
但是,这不适用于 s2
和 s3
。
试试这个:
String numberOnly = s1.replaceAll("[^0-9]", "");
int num = Integer.parseInt(numberOnly);
或者短的:
int num = Integer.parseInt(s1.replaceAll("[^0-9]", ""));
代码同样适用于s2和s3!
你可以检查字符串中的第一个字符是否是字母,如果是,则执行
Integer.parseInt(s1.substring(1))
表示从第二个字符开始解析
您可以使用 java.util.regex 包,其中包含两个最重要的包 类
1) 模式Class
2)匹配器Class
使用此 类 获得您的解决方案。
有关模式和匹配器的更多详细信息Class请参阅下文link
http://www.tutorialspoint.com/java/java_regular_expressions.htm
下面是完整的例子
public class Demo {
public static void main(String[] args) {
String s1 = "6A";
String s2 = "14T";
String s3 = "S32";
Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher(s3);
while (m.find())
{
System.out.println(m.group());
}
}
}
如果您需要字符串并想跳过数值,请使用以下模式。
Pattern p = Pattern.compile("[a-zA-Z]");
你可以做这样的事情:
public static int getNumber(String text){
return Integer.parseInt(text.replaceAll("\D", ""));
}
public static String getChars(String text){
return text.replaceAll("\d", "");
}
public static void main(String[] args) {
String a = "6A";
String b = "14T";
String c = "S32";
System.out.println(getNumber(a));
System.out.println(getChars(a));
System.out.println(getNumber(b));
System.out.println(getChars(b));
System.out.println(getNumber(c));
System.out.println(getChars(c));
}
输出:
6
一种
14
吨
32
S
假设有三个字符串:
String s1 = "6A";
String s2 = "14T";
String s3 = "S32";
我需要提取数值(即 6、14 和 32)和字符(A、T 和 S)。
如果第一个字符始终是数字,则此代码有效:
int num = Integer.parseInt(s1.substring(0,1));
但是,这不适用于 s2
和 s3
。
试试这个:
String numberOnly = s1.replaceAll("[^0-9]", "");
int num = Integer.parseInt(numberOnly);
或者短的:
int num = Integer.parseInt(s1.replaceAll("[^0-9]", ""));
代码同样适用于s2和s3!
你可以检查字符串中的第一个字符是否是字母,如果是,则执行
Integer.parseInt(s1.substring(1))
表示从第二个字符开始解析
您可以使用 java.util.regex 包,其中包含两个最重要的包 类
1) 模式Class
2)匹配器Class
使用此 类 获得您的解决方案。
有关模式和匹配器的更多详细信息Class请参阅下文link
http://www.tutorialspoint.com/java/java_regular_expressions.htm
下面是完整的例子
public class Demo {
public static void main(String[] args) {
String s1 = "6A";
String s2 = "14T";
String s3 = "S32";
Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher(s3);
while (m.find())
{
System.out.println(m.group());
}
}
}
如果您需要字符串并想跳过数值,请使用以下模式。
Pattern p = Pattern.compile("[a-zA-Z]");
你可以做这样的事情:
public static int getNumber(String text){
return Integer.parseInt(text.replaceAll("\D", ""));
}
public static String getChars(String text){
return text.replaceAll("\d", "");
}
public static void main(String[] args) {
String a = "6A";
String b = "14T";
String c = "S32";
System.out.println(getNumber(a));
System.out.println(getChars(a));
System.out.println(getNumber(b));
System.out.println(getChars(b));
System.out.println(getNumber(c));
System.out.println(getChars(c));
}
输出:
6 一种 14 吨 32 S