Java REGEX to match an exact number of digits in a string

后端 未结 5 1801
天涯浪人
天涯浪人 2020-12-11 04:19

I tried to find the answer to my problem in the questions history but they just come back in more than one thousand and after scanning through a few tens of matching answers

5条回答
  •  眼角桃花
    2020-12-11 05:04

     public static String splitting(String str, int num){
        String arr[] = str.split("[^0-9]");
        for(String s:arr)
            if(s.length() == num)
                return s;
        return null;
    }
    

    test with

     public static void main(String[] args) {
        String s =  "Some text 987654321 and some more text 123456 and some other text again 654321 and more text in the end";
        System.out.println(splitting(s, 6));
    }
    

    output is

      123456
    

提交回复
热议问题