hacker
hacker

Reputation: 392

Regex for int Array

I need to validate a string argument if it can be converted to an int Array.

String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";

test2.matches(pattern2) //returns false as i requires , in the end

Is there any way to ignore last ' , '

Upvotes: 1

Views: 5313

Answers (5)

Diego Yednak
Diego Yednak

Reputation: 31

You can try

Pattern = "^\d+(,\d+)*$"

text = "10,5,10"    (TRUE)
text = "10,5,10,"   (FALSE)
text = "10,5,10 "   (FALSE)

Upvotes: 0

Bohdan Petrenko
Bohdan Petrenko

Reputation: 1175

Regex for both array and single element

(\d|\[(\d|,\s*)*])

Upvotes: 1

sharad_kalya
sharad_kalya

Reputation: 285

Since I don't know how to use regex and if I were in your place then this would have been my way to do so

String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
    ar[i] = Integer.parseInt(str[i]);
}

The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).

Upvotes: -1

hwnd
hwnd

Reputation: 70732

Use a group construct to specify that digits should be followed by (, digits) ...

\\d+(?:,\\d+)+

Upvotes: 6

TheLostMind
TheLostMind

Reputation: 36304

This regex will work for you (checks for a "valid array") :

public static void main(String[] args) {
    String s = "18,32,5,8,10";
    System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}

Checks and fails for:

  1. multiple continuous commas
  2. comma at beginning
  3. comma at end

Upvotes: 0

Related Questions