user1472150 user1472150 - 1 month ago 6
Java Question

How to get fix size numbers from string array in Java

I'm new to Java. I have a string array like this,

String [] numArray = {"1234", "-1234" , "abcd", "12ab","2345","1a34"};


I want to get 4 digt positive numbers from this array.


Expected Output : 1234 2345

Answer

Try this Pattern,

Pattern pattern = Pattern.compile("\\d{4}"); 
String [] numArray = {"1234", "-1234" , "abcd", "12ab","2345","1a34"};

for(String num: numArray){
    if(pattern.matcher(num).matches()){
         System.out.print(num + " ");
    }
}
Comments