Java正则表达式实现及特定格式控制台参数验证疑问
Hey, let's work through this code validation problem you're facing in Java. Using the java.util.regex package is the right approach here, and I'll walk you through exactly how to implement it step by step.
First, we need a regex that matches either XXX-XXXX or XXX-XXXX-XXXX where each X is a digit (0-9). Here's the regex to use:
^\\d{3}-\\d{4}(-\\d{4})?$
Let me break this down so you understand what each part does:
^: Anchors the match to the start of the string (ensures nothing comes before the valid format)\\d{3}: Matches exactly 3 digits (the first XXX part)-: Matches the literal hyphen\\d{4}: Matches exactly 4 digits (the XXXX part)(-\\d{4})?: The?makes this entire group optional. Inside, we have another hyphen followed by 4 digits (the second XXXX segment for the longer format)$: Anchors the match to the end of the string (ensures nothing comes after the valid format)
Here's a complete example that reads the console arguments, validates the code format, and handles basic error checking:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class CodeValidator { public static void main(String[] args) { // First, check if we have exactly 2 arguments if (args.length != 2) { System.err.println("Error: Please provide two arguments."); System.err.println("Usage: java CodeValidator <ini-file-path> <code>"); System.exit(1); } String iniPath = args[0]; String inputCode = args[1]; // Compile the regex pattern (pre-compiling is efficient if you reuse it) String codeRegex = "^\\d{3}-\\d{4}(-\\d{4})?$"; Pattern pattern = Pattern.compile(codeRegex); Matcher matcher = pattern.matcher(inputCode); // Validate the code format if (matcher.matches()) { System.out.println("Code format is valid!"); // Now you can proceed to load the .ini file using iniPath // ... your file loading logic here ... } else { System.err.println("Invalid code format!"); System.err.println("Please use either XXX-XXXX or XXX-XXXX-XXXX where X is a digit (0-9)."); System.exit(1); } } }
- Full String Match: Using
matcher.matches()ensures the entire input string matches the regex. If you usedfind()instead, it would match any substring that fits, which isn't what we want here—we need the entire code parameter to be valid. - Regex Compilation: Pre-compiling the pattern with
Pattern.compile()is a good practice, especially if you'll be validating multiple codes. It saves processing time compared to usingString.matches()directly (which compiles the regex every time). - Escape Characters: In Java, backslashes (
\) need to be escaped with another backslash, so\dbecomes\\din the string literal.
That should cover everything you need to validate the code format properly. If you hit snags with the .ini file loading part, feel free to follow up!
内容的提问来源于stack exchange,提问作者victor26567

