Java正则匹配含数字、指定特殊字符及X/x的手机号
Hey there! That "Dangling meta character '*'" error happens because you're using * as a literal character but treating it like a regex quantifier (which expects to follow a pattern element). Let's build the correct regex for your needs step by step.
The Correct Java Regex
To match phone numbers containing only your allowed characters (digits 0-9, #, *, -, _, space, (, ), +, ?, and x/X), here's the right pattern:
String phoneRegex = "^[0-9#*\\-_ ()+?xX]+$";
Breakdown of the Regex
Let's break down each part so you understand what's happening:
^: Anchors the match to the start of the string (ensures no invalid characters before your allowed ones)[0-9#*\\-_ ()+?xX]: A character class that matches any single allowed character:0-9: Matches any digit from 0 to 9#*: Matches literal#and*(these don't need escaping inside a character class)\\-: Escaped hyphen-(we escape it here to avoid confusion with a range operator; alternatively, you could place it at the start/end of the character class like[0-9#*_ ()+?xX-]to skip escaping): Matches a literal space(): Matches literal parentheses (no escaping needed inside a character class)+?: Matches literal+and?(again, safe inside the character class)xX: Matches both lowercase and uppercasex
+: Requires the character class to match 1 or more times (use*instead if you want to allow empty strings, though that probably doesn't make sense for phone numbers)$: Anchors the match to the end of the string (ensures no invalid characters after your allowed ones)
Example Java Code
Here's a quick test to verify the regex works as expected:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class PhoneValidator { public static void main(String[] args) { String regex = "^[0-9#*\\-_ ()+?xX]+$"; Pattern pattern = Pattern.compile(regex); // Test cases String[] testNumbers = { "123-456-7890", // Valid "(123) 456*7890x", // Valid "123+456?7890X", // Valid "123_456#7890", // Valid "*123-456*", // Valid "123abc456", // Invalid (contains 'abc') "123@456", // Invalid (contains '@') "" // Invalid (empty string, use * instead of + to allow this) }; for (String number : testNumbers) { Matcher matcher = pattern.matcher(number); System.out.printf("Number: '%s' -> %s%n", number, matcher.matches() ? "VALID" : "INVALID"); } } }
Why You Got the "Dangling meta character '*'" Error
That error pops up when you use * as a quantifier without a preceding pattern element (like writing ^*abc instead of .*abc), or if you forget to put a literal * inside a character class/escape it. In your case, you likely had * outside the character class where it was being treated as a quantifier instead of a literal character.
内容的提问来源于stack exchange,提问作者Snehal Gupta

