Friends
I have the following Regex "^[0-9]{1,12}+(\\\\.[0-9]{1,4})?$"
that allows the following values
123456789012.1234 which is a valid decimal value {12,4}
123456789012 which is a valid integer value etc
but it doesn't allow value like .1235 etc , how should I modify above Regex so that it also allows values like .123 and 123. etc
I guess,
^(?:[0-9]{1,12}(?:\\.[0-9]{0,4})?|\\.[0-9]{0,4})$
might be somewhat close.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "^(?:[0-9]{1,12}(?:\\.[0-9]{0,4})?|\\.[0-9]{0,4})$";
final String string = "123456789012.1234\n"
+ "123456789012\n"
+ ".1235\n"
+ ".123\n"
+ "123.\n"
+ ".12345\n"
+ "0.12345";
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));
}
}
}
}
Full match: 123456789012.1234
Full match: 123456789012
Full match: .1235
Full match: .123
Full match: 123.
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com . You can watch the matching steps or modify them in this debugger link , if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
jex.im visualizes regular expressions:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.