import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:[1-9][0-9]*?,?[0-9]{1,2}|[0](?:,[0-9]{1,2})?|)$";
final String string = "Input amount is not a string (only number 0-9)\n"
+ "Adwad,321 d3,232,123,A;d,aw\n"
+ "123456789\n\n"
+ "Separator must be \",\"\n"
+ "12.1\n"
+ "12,1\n\n"
+ "I need max 2 decimal places\n"
+ "17,234236\n"
+ "17,23\n\n"
+ "I can't accept any characters, except of numbers 0-9 and \",\"\n"
+ "321d,3e16\n"
+ "-323,3\n"
+ "123,45\n\n"
+ "Input amount cannot be less than 0\n"
+ "-1\n"
+ "0\n"
+ "0,01\n\n"
+ "Input amount has to start from a number\n"
+ "a31233\n"
+ ",321\n"
+ "1232\n\n"
+ "extra; does not allow \"fake/mal-formatted\" numbers\n"
+ "0312312\n"
+ "032312\n\n"
+ "extra 2; doesnt last character to be \",\"\n"
+ "1,0\n"
+ "1,\n"
+ "0,12\n"
+ "0,\n"
+ "3123,";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html