Regex To Match Digit Values Separated By Space, But Whole String Doesn't End With Space
I implement an EditText that allows to input prices separated by a space. The prices can be both integer and decimal values. For example: 3900 156.2 140.38 200 10 So, I've found
Solution 1:
I would suggest the following pattern:
^\d+(?:\.\d+)?(?:\s+\d+(?:\.\d+)?)*$
In plain English, this says to match a (possibly) decimal number, followed by one or more whitespace characters, and another (possibly) decimal number, that happening zero or more times.
Have a look at the demo link below.
Demo
But since you're using Java, I can suggest an alternative here. Since you will likely have to access each number, you could instead split the string coming from the EditText
by space, and then check each "number" to make sure it really is a number. Something like this:
String input ="3900 156.2 140.38 200 10";
String[] nums = input.split("\\s+");
for (String num : nums) {
if (num.matches("\\d+(?:\\.\\d+)?")) {
// then process this as a number
}
}
Solution 2:
You can also use (almost) the same pattern you provided:
(\d+([.]\d{1,2})? )*(\d+([.]\d{1,2})?)
This is less flexible than Tim's answer (like: if you put more than one space between numbers it will fail, etc) but it might be useful anyway.
Post a Comment for "Regex To Match Digit Values Separated By Space, But Whole String Doesn't End With Space"