0

I have a converter that will convert an array of int into a String.

**EDIT** [1, 2, -45, 678] -> "1 2 -45 678";
[1] -> "1"

Into this converter, I have a supportFromString method to identify if the string can be converted back into an array.

I though of using regex to do so, but I can't find a good match. I tried "\\d+\\s" and "[\\d+]\\s" but s.matches(pattern) returns false.

Any suggestion? If one non-numeric character is found, it's not valid.

EDIT Here is the toString method of the converter

@Override
public String toString(Object o, ConverterContext converterContext) {
    StringBuilder builder = new StringBuilder();

    for (Integer integer : ((Integer[]) o)) {
        if (builder.toString().length() > 0) {
            builder.append(" ");
        }

        builder.append(integer);
    }

    return builder.toString();
}
P. Lalonde
  • 694
  • 1
  • 7
  • 17
  • http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java – gtgaxiola Jan 07 '14 at 16:55
  • 1
    What happened when you tried those regexes? A good question explains what you've tried *and why it didn't work*. – Duncan Jones Jan 07 '14 at 16:58
  • You could match the string with the following regex: `[0-9 ]+` and compare it to the original string to see if they are equal. – tenub Jan 07 '14 at 16:58
  • s.matches(_pattern_) returns false – P. Lalonde Jan 07 '14 at 16:59
  • @tenub, this will match only single digits followed by a space, but I could get any valid integer into my array. – P. Lalonde Jan 07 '14 at 17:01
  • Are you looking for exact matches only? I.e. must there be only one space between all numbers and no trailing space at the end? – Duncan Jones Jan 07 '14 at 17:06
  • @P.Lalonde Did you notice that the `converterContext` variable is never used in the `toString` method... – Stephan Jan 07 '14 at 17:06
  • @Alex, yes, this is because my converter is registered into a third party library, I need to match their Interface, but this object contains nothing usefull for my converter to convert values. – P. Lalonde Jan 07 '14 at 17:08
  • @Lalonde, tenub's regex matches any combination of at least one number or space. It should work for the given string. Are you trying to match something more specific? – mdl Jan 07 '14 at 17:09
  • @mdl, I was not clear into the example, let me edit my post, integers can also be negative. – P. Lalonde Jan 07 '14 at 17:17
  • @P.Lalonde The pattern `\\d+\\s+` doesn't match because the last number is not followed by a blank character (space). See this answser:http://stackoverflow.com/a/20977684/363573 – Stephan Jan 07 '14 at 17:20

6 Answers6

2

I would test the string against the following regex:

[^\d ]

If you get any results it means you have something else other than a digit (\d) or a space

Joao Raposo
  • 135
  • 8
1

Try this code :

String pattern = "(-?\\d+\\s*)+";
String test = "1 -5 2 45 678";

System.out.println(test.matches(pattern));

Output

True

If you want to find the digits, use this pattern alone: -?\\d+\\s*.

Stephan
  • 41,764
  • 65
  • 238
  • 329
1
static Pattern validPattern = Pattern.compile("^(\\-{0,1}\\d+\\s)*(\\-){0,1}\\d+$");

public static void main(String[] args) {
    isStringValid("1 2 3 4 5");
    isStringValid("1 26 35 44 53");
    isStringValid("1 2a 3s 4 5");
    isStringValid("1234");
    isStringValid("1");
    isStringValid("1 ");
    isStringValid("a b c");
    isStringValid("1 b c");
    isStringValid("1 1 2 33333");
    isStringValid("-1 1 2 33333");
    isStringValid("1 1 2 -33333");
    isStringValid("1 1 2 ----33333");
    isStringValid("---1 1 2 -33333");
}

public static boolean isStringValid(String s){
    s = s.trim();
    boolean b = validPattern.matcher(s).find();

    if (b){
        System.out.printf("%s: is valid.\n", s);
    }else{
        System.out.printf("%s: is NOT valid.\n", s);
    }

    return(b);
}

Result:

1 2 3 4 5: is valid.
1 26 35 44 53: is valid.
1 2a 3s 4 5: is NOT valid.
1234: is valid.
1: is valid.
1: is valid.
a b c: is NOT valid.
1 b c: is NOT valid.
1 1 2 33333: is valid.
-1 1 2 33333: is valid.    
1 1 2 -33333: is valid.
1 1 2 ----33333: is NOT valid.
---1 1 2 -33333: is NOT valid.
superm4n
  • 314
  • 2
  • 9
0

This is the regex you can use to test if the string is a number optionally followed by other numbers separated by one or more spaces:

"(0|-?[1-9][0-9]*)(\\s+(0|-?[1-9][0-9]*))*"

EDIT: Included negative integers and excluded leading zeros.

aalku
  • 2,860
  • 2
  • 23
  • 44
0

Here my take, which handles negative numbers.

   import  java.util.regex.Matcher;
   import  java.util.regex.Pattern;
   import  java.util.Arrays;
/**
   <P>java IntArrayToStringToIntArray</P>
 **/
public class IntArrayToStringToIntArray  {
   private static final Pattern pDigits = Pattern.compile("-?\\d+");
   public static final void main(String[] igno_red)  {

      String sArray = Arrays.toString(new int[]{1, 2, -45, 678});
         System.out.println("---The array: " + sArray);
         System.out.println(isSafeToConvertToStringedArrayToIntArray(sArray));
         int[] ai = getIntArrayFromToStringedArray(sArray);
         for(int i : ai)  {
            System.out.println(i);
         }
         System.out.println();

      sArray = Arrays.toString(new int[]{1});
         System.out.println("---The array: " + sArray);
         System.out.println(isSafeToConvertToStringedArrayToIntArray(sArray));
         ai = getIntArrayFromToStringedArray(sArray);
         for(int i : ai)  {
            System.out.println(i);
         }
         System.out.println();

      sArray = "bogus";
         System.out.println("---The array: " + sArray);
         System.out.println(isSafeToConvertToStringedArrayToIntArray(sArray));
   }


   //Assumes the string is formatted as if by Arrays.toString(int[])
   public static final boolean isSafeToConvertToStringedArrayToIntArray(String s_ofInts)  {
      //Eliminate the surrounding square brackets
      s_ofInts = s_ofInts.substring(1, s_ofInts.length() - 1);
      String[] as = s_ofInts.split(", ");

      for(String s : as)  {
         Matcher m = pDigits.matcher(s);
         if(!m.matches())  {
            return  false;
         }
      }

      return  true;
   }


   //Assumes the string is formatted as if by Arrays.toString(int[])
   public static final int[] getIntArrayFromToStringedArray(String s_ofInts)  {
      //Eliminate the surrounding square brackets
      s_ofInts = s_ofInts.substring(1, s_ofInts.length() - 1);

      String[] as = s_ofInts.split(", ");

      int[] ai = new int[as.length];
      for(int i = 0; i < as.length; i++)  {
         String s = as[i];
         Matcher m = pDigits.matcher(s);
         if(m.matches())  {
            ai[i] = Integer.parseInt(s);
         }  else  {
            throw  new IllegalArgumentException("getIntArrayFromToStringedArray: Element " + i + " in s_ofInts is not an int: \"" + s + "\".");
         }
      }
      return  ai;
   }
}
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • I was looking for a regex. – P. Lalonde Jan 07 '14 at 17:43
  • The point of your question is to create a `supportFromString` function. A regex is one part of the picture. I created your function exactly as specified (despite the different name), using your exact demo-data. And there *IS* a regex in there. A downvote for all this work really sucks. – aliteralmind Jan 07 '14 at 17:47
-1

You could read the entire input line from scanner, then split the line by,then you have a String[], parse each number into int[] with index one to one matching(assuming valid input and no NumberFormatExceptions)like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}

Dharmendra
  • 571
  • 5
  • 12
  • Performance wise, I am not sure this is the best solution, I really think regex should be the best thing to do. – P. Lalonde Jan 07 '14 at 17:06
  • 1
    Why is your answer littered with `
    `? Just start a new line in the editor if you want a new line. And place your code in a code block. See the [editing help](http://stackoverflow.com/editing-help) for more info.
    – Duncan Jones Jan 07 '14 at 17:07
  • Why in the world are you downvoting answers you don't agree with, or happen to be a different flavor than you might choose? Your question does not specify "performance must be optimal". – aliteralmind Jan 07 '14 at 17:51
  • Clearly the intent here is to help you. Downvoting does not make us want to help. – aliteralmind Jan 07 '14 at 18:00