Java正则表达式匹配小写字母加右括号问题求助
Hey there! Let's break down why your regex [a-d]\) works in Regexpal but not in Java, and fix it right away.
The Root Cause
The most likely issue here is how Java's String.matches() method behaves. Unlike Regexpal (which scans the input string to find any matching substring), matches() requires the regex to match the entire input string from start to finish.
For example, if you run this code:
String target = "a) option a b) option b c) option c d) option d"; boolean result = target.matches("[a-d]\\)"); // Returns false
It returns false because your regex only matches a single pattern like a) or b), but your target string is much longer—matches() can't match the whole thing with that regex.
The Fix
To replicate Regexpal's behavior (finding all matching substrings in your target string), use Java's Pattern and Matcher classes with the find() method. Here's a working example:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatcherExample { public static void main(String[] args) { String target = "a) option a b) option b c) option c d) option d"; // Inside a character class [], ')' doesn't need escaping—so "[a-d])" works too Pattern pattern = Pattern.compile("[a-d]\\)"); Matcher matcher = pattern.matcher(target); // Loop through all matches while (matcher.find()) { System.out.println("Found match: " + matcher.group()); } } }
When you run this code, it will output:
Found match: a) Found match: b) Found match: c) Found match: d)
Bonus: Check for Any Match
If you only need to know if at least one match exists (instead of listing all), you can simplify it to:
boolean hasMatch = matcher.find(); // Returns true if any match is found
内容的提问来源于stack exchange,提问作者Alex F

