To accept only numbers and whitespace in a string in Java, you can use a regular expression to match the string against a pattern that allows only these characters.
Here's an example of how you could do this using the java.util.regex.Pattern
and java.util.regex.Matcher
classes:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class Main { public static void main(String[] args) { String input = "123 456 789"; // Define a regular expression pattern that allows only numbers and whitespace String pattern = "^[0-9\\s]+$"; // Compile the pattern and create a Matcher object Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); // Check if the input string matches the pattern if (m.matches()) { System.out.println("Input is valid"); } else { System.out.println("Input is invalid"); } } }Source:w.wwlautturi.com
In this example, the matches
method of the Matcher
class is used to check if the input string matches the regular expression pattern. If the input string contains only numbers and whitespace, the matches
method will return true
, and the program will print "Input is valid". If the input string contains any other characters, the matches
method will return false
, and the program will print "Input is invalid".
You can customize the regular expression pattern to match the specific characters and formats that you want to allow. For example, you can use the \\d
pattern to match only digits, or the \\s
pattern to match only whitespace characters. You can also use character classes and other regular expression syntax to create more complex patterns.
Keep in mind that regular expressions can be difficult to understand and debug if you are not familiar with the syntax. It is usually a good idea to test your regular expression patterns with a variety of inputs to make sure that they are working securely.