如何验证字符串为有效的USSD码?求正确的Java正则表达式
Validating USSD Codes with Regex
Let's work through this USSD regex problem together. First, let's restate your requirements clearly to make sure we cover every base:
- Must start with
* - Can include digits (0-9) or single
*characters (no consecutive**allowed) - Must end with exactly one
#(no other#characters anywhere in the string)
The Correct Regex Pattern
Here's the regex that satisfies all your rules:
public static final Pattern USSD = Pattern.compile("^\\*(?:\\d|\\*(?!\\*))*#$");
Breaking Down the Regex
Let's unpack each part so you understand how it works:
^\\*: Ensures the string starts with a single*(we escape*because it’s a special character in regex)(?:\\d|\\*(?!\\*))*: A non-capturing group that matches any number of valid middle characters:\\d: Matches any digit from 0-9\\*(?!\\*): Matches a single*only if there isn’t another*right after it (this stops consecutive**from being allowed)- The trailing
*means this group can repeat zero or more times (so even a simple*#counts as valid)
#$: Ensures the string ends with exactly one#, and since we’re using^(start) and$(end) anchors, there’s no space for extra#characters anywhere else.
Test Cases
Let’s verify with your examples plus some edge cases to confirm it works:
public class UssdValidationTest { public static final Pattern USSD = Pattern.compile("^\\*(?:\\d|\\*(?!\\*))*#$"); public static void main(String[] args) { // Valid scenarios System.out.println(USSD.matcher("*123#").matches()); // true System.out.println(USSD.matcher("*1*2*3#").matches()); // true System.out.println(USSD.matcher("*#").matches()); // true System.out.println(USSD.matcher("*987*65*4321#").matches()); // true // Invalid scenarios System.out.println(USSD.matcher("**123#").matches()); // false (consecutive *) System.out.println(USSD.matcher("*123##").matches()); // false (extra #) System.out.println(USSD.matcher("123#").matches()); // false (doesn't start with *) System.out.println(USSD.matcher("*123").matches()); // false (doesn't end with #) System.out.println(USSD.matcher("*1**2#").matches()); // false (consecutive *) } }
This regex should handle all your use cases perfectly. If you need to adjust for any edge cases we didn't cover, just let me know!
内容的提问来源于stack exchange,提问作者GV_FiQst
相关产品推荐
相关产品推荐

