You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java正则表达式匹配小写字母加右括号问题求助

Why Your Regex Fails in Java (But Works in Regexpal)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:44:24