简体   繁体   English

如何从字符串获取数字和非数字值

[英]How to obtain numeric and non-numeric values from a String

Let's say there are three strings: 假设有三个字符串:

String s1 = "6A";
String s2 = "14T";
String s3 = "S32";

I need to extract numeric values (ie 6,14 and 32) and characters (A,T and S). 我需要提取数值(即6,14和32)和字符(A,T和S)。

If the first character was always a digit, then this code would work: 如果第一个字符始终是数字,则此代码将起作用:

int num = Integer.parseInt(s1.substring(0,1));

However, this is not applicable to s2 and s3 . 但是,这不适用于s2s3

Try this: 尝试这个:

String numberOnly = s1.replaceAll("[^0-9]", "");
int num = Integer.parseInt(numberOnly);

Or the short one: 或简短的一个:

int num = Integer.parseInt(s1.replaceAll("[^0-9]", ""));

The code is applicable for s2 and s3 as well! 该代码也适用于s2和s3!

You can make something like that: 你可以做这样的事情:

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));
}

Output: 输出:

6 A 14 T 32 S 6 A 14 T 32 S

You can use java.util.regex package which is consists two most important classes 您可以使用由两个最重要的类组成的java.util.regex

1) Pattern Class 1)模式类

2) Matcher Class 2)配对班

Using this classes to get your solution. 使用此类来获取您的解决方案。

For more details about Pattern and Matcher Class refer below link 有关模式和匹配器类的更多详细信息,请参见下面的链接

http://www.tutorialspoint.com/java/java_regular_expressions.htm http://www.tutorialspoint.com/java/java_regular_expressions.htm

Below is the complete example 以下是完整的示例

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());
    }

}
}

If you need string and wants to skip numeric value then use below pattern. 如果您需要字符串并且想跳过数值,则使用以下模式。

Pattern p = Pattern.compile("[a-zA-Z]");

Yo can check whether first character in a string is a letter if yes then do 您可以检查字符串中的第一个字符是否为字母,如果是,则可以

Integer.parseInt(s1.substring(1))

Means parse from second character 表示从第二个字符开始解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM