Home > Blockchain >  Regex seperate 2 numbers by komma
Regex seperate 2 numbers by komma

Time:10-04

I'm trying to make a regex to allow only a case of a number then "," and another number or same case seperated by ";" like

  1. 57,1000
  2. 57,1000;6393,1000

So far i made this: Pattern.compile("\\b[0-9;,]{1,5}?\\d ;([0-9]{1,5},?) ").matcher("57,1000").find(); which work if case is 57,1000;6393,1000 but it also allow letters and don't work when case 57,1000

CodePudding user response:

try Regex "(\d ,\d (;\d ,\d )?)"

@Test
void regex() {
    
    Pattern p = Pattern.compile("(\\d ,\\d )(;\\d ,\\d )?"); 
    
    Assertions.assertTrue(p.matcher("57,1000").matches());
    Assertions.assertTrue(p.matcher("57,1000;6393,1000").matches());
    
}

CodePudding user response:

How about like this. Just look for two numbers separated by a comma and capture them.

String[] data = {"57,1000",
"57,1000;6393,1000"};

Pattern p = Pattern.compile("(\\d ),(\\d )");
for (String str : data) {
    System.out.println("For String : "   str);
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group(1)   " "   m.group(2));
    }
    System.out.println();
}

prints

For String : 57,1000
57 1000

For String : 57,1000;6393,1000
57 1000
6393 1000

If you just want to match those, you can do the following: It matches a single instance of the string followed by an optional one preceded by a semi-colon.

String regex = "(\\d ,\\d )(;(\\d ,\\d ))?";
for (String str : data) {
    System.out.println("Testing String "   str   " : "  str.matches(regex));
}

prints

Testing String 57,1000 : true
Testing String 57,1000;6393,1000 : true

  •  Tags:  
  • java
  • Related