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 keywordsANDorORas whole units (prevents partial matches likeANorOfrom being allowed)\d: Matches any digit (0-9, equivalent to[0-9])\s: Matches any whitespace character (spaces, tabs, etc. – adjust toif 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
相关产品推荐
相关产品推荐

