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

Java正则表达式校验需求:匹配数字、括号、AND/OR及空格

Fixing Your Regex for Java Validation

Got it, let's sort out that regex you're working on. The key issue with your previous attempts is that you were trying to fit AND/OR into a character class (which only handles single characters), but those are multi-word keywords that need to be matched as whole units.

The Correct Regex

Here's a regex that meets all your requirements:

^((AND|OR)|\d|\s|\(|\))+$

Breakdown of the Pattern

Let's break down each part so you understand how it works:

  • ^ and $: Anchors to ensure the entire string is validated (no extra characters before or after allowed content)
  • (AND|OR): Matches the complete keywords AND or OR as whole units (prevents partial matches like AN or O from being allowed)
  • \d: Matches any digit (0-9, equivalent to [0-9])
  • \s: Matches any whitespace character (spaces, tabs, etc. – adjust to if you only want literal spaces)
  • \( and \): Matches opening and closing parentheses (we don't enforce proper nesting here since your stack-based code handles that)
  • +: Ensures there's at least one valid character in the string (blocks empty inputs)

Testing Against Your Examples

This regex will correctly validate all your sample inputs:

  • Valid: 1OR2, 2, 1 OR 2 OR 15, ( 2OR3) AND 1, (12AND13 AND1)OR(4 AND5), ((2AND3 AND 1)OR(4AND5))AND6
  • Also valid (as requested): ())34AND(4 (even with mismatched parentheses, since your stack code handles that check separately)

Java Implementation Example

Here's how you'd use this in your Java code:

import java.util.regex.Pattern;

public class ValidationExample {
    public static void main(String[] args) {
        String validationRegex = "^((AND|OR)|\\d|\\s|\\(|\\))+$";
        Pattern pattern = Pattern.compile(validationRegex);
        
        // Test a valid input
        String validInput = "(12AND13 AND1)OR(4 AND5)";
        System.out.println(pattern.matcher(validInput).matches()); // Outputs true
        
        // Test an invalid input (contains 'X')
        String invalidInput = "1ORX2";
        System.out.println(pattern.matcher(invalidInput).matches()); // Outputs false
    }
}

Optional: Case Insensitivity

If you need to allow lowercase or mixed-case versions like and or Or, add the case-insensitive flag ((?i)) to the regex:

^((?i)AND|OR|\d|\s|\(|\))+$

内容的提问来源于stack exchange,提问作者Mikke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:59:07