简体   繁体   English

Java正则表达式将数字和字符串分开

[英]java regex separate numbers from strings

I have got strings like: 我有这样的字符串:

BLAH00001 BLAH00001

DIK-11 DIK-11

DIK-2 DIK-2

MAN5 MAN5

so all the strings are a kind of (sequence any characters)+(sequence of numbers) 所以所有的字符串都是一种(任意字符序列)+(数字序列)

and i want something like this: 我想要这样的事情:

1 1

11 11

2 2

5

in order to get those integer values, i wanted to separate the char sequence and the number sequence an do something like Integer.parseInt(number_sequence) 为了获得这些整数值,我想将char序列和数字序列分开,然后执行Integer.parseInt(number_sequence)

Is there something that does this job? 有什么可以做的工作吗?

greetings 问候

Try this: 尝试这个:

public class Main {
    public static void main(String[]args) {
        String source = "BLAH00001\n" +
                "\n" +
                "DIK-11\n" +
                "\n" +
                "DIK-2\n" +
                "\n" +
                "MAN5";
        Matcher m = Pattern.compile("\\d+").matcher(source);
        while(m.find()) {
            int i = Integer.parseInt(m.group());
            System.out.println(i);
        }
    }
}

which produces: 产生:

1
11
2
5
String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
 for(String g:a)
  System.out.println(Integer.valueOf(g.split("^[A-Z]+\\-?")[1]));

 /*******************************  
   Regex Explanation :
     ^  --> StartWith
    [A-Z]+ --> 1 or more UpperCase
    \\-? --> 0 or 1 hyphen   
*********************************/
 Pattern p = Pattern.compile("^[^0-9]*([0-9]+)$");
 Matcher m = p.matcher("ASDFSA123");
 if (m.matches()) {
    resultInt = Integer.parseInt(m.group(1)));
 }

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

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