如何实现标识符校验:任意位置含*即无效并允许下划线
Fixing Java Identifier Validation to Block Any
* and Allow Underscores Let's tackle this validation problem head-on. Your original code only checks the first character for *, which is why inputs like g*g slip through. We need to adjust the logic to scan the entire identifier and enforce the rules properly.
Key Requirements Recap
- Reject any identifier that contains
*(any position) - Allow underscores (
_) anywhere (start, middle, end) - Block all other special characters
- First character must be a letter or underscore (aligns with standard identifier conventions)
Step-by-Step Fix
- Scan every character for
*: As soon as we find one, we can immediately mark the identifier as invalid. - Validate the first character: Must be a letter (
Character.isLetter()) or underscore. - Validate remaining characters: Each one must be a letter, digit (
Character.isDigit()), or underscore.
Corrected Complete Code Example
Here's a full implementation with proper validation logic:
import java.util.Scanner; public class IdentifierValidator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an identifier to validate: "); String input = scanner.nextLine(); if (isValidIdentifier(input)) { System.out.println("Valid identifier!"); } else { System.out.println("Invalid identifier!"); } scanner.close(); } private static boolean isValidIdentifier(String identifier) { // Handle empty or null input if (identifier == null || identifier.isEmpty()) { return false; } char[] chars = identifier.toCharArray(); // Check each character dynamically for (int i = 0; i < chars.length; i++) { char c = chars[i]; // Reject immediately if any character is '*' if (c == '*') { return false; } // Validate first character rule if (i == 0) { if (!Character.isLetter(c) && c != '_') { return false; } } // Validate non-first character rules else { if (!Character.isLetterOrDigit(c) && c != '_') { return false; } } } // All checks passed return true; } }
Test Cases to Verify
Let's test this with your edge cases and other scenarios:
- Valid:
g_g,_test123,MyIdentifier,a_b_c - Invalid:
g*g(contains *),*gg(starts with *),g!g(has exclamation),123test(starts with digit),g@3(has @)
This implementation dynamically scans every character, so no matter where * appears, it gets caught. It also properly allows underscores while blocking all other special characters.
内容的提问来源于stack exchange,提问作者ehelp fit
相关产品推荐
相关产品推荐

