有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有这样的字符串:

BLAH00001

DIK-11

DIK-2

男士5

所以所有的字符串都是一种(任意字符序列)+(数字序列)

我想要这样的东西:

一,

十一,

二,

五,

为了得到这些整数值,我想将字符序列和数字序列分开,然后执行类似Integer.parseInt(number_sequence)

有什么东西可以做这项工作吗

问候


共 (4) 个答案

  1. # 1 楼答案

    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   
    *********************************/
    
  2. # 3 楼答案

     Pattern p = Pattern.compile("^[^0-9]*([0-9]+)$");
     Matcher m = p.matcher("ASDFSA123");
     if (m.matches()) {
        resultInt = Integer.parseInt(m.group(1)));
     }
    
  3. # 4 楼答案

    试试这个:

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

    产生:

    1
    11
    2
    5